reactjs 如何使用React Navigation将参数发送到另一个屏幕而无需移动?

omqzjyyz  于 2022-12-29  发布在  React
关注(0)|答案(2)|浏览(110)

我知道你可以做导航。navigate("address",{/* params go here */将参数发送到另一个屏幕。但是你必须导航到那里。有没有一种方法可以在不导航的情况下发送参数?
我有一个有多个屏幕的应用程序。我想从另一个组件中更新useState,方法是更新它的参数,这样就可以显示一个按钮。但是我不想导航到那里,我只想更新它,这样当用户确实转到那里时,按钮就会出现。
就像这样:

const currentComponent = (navigation) {
return (
  <Button onPress={navigation.updateParams("otherComponent", {shouldShowValue: true})} />
  )
}



const otherComponent = (route, navigation) {
 const {shouldShowValue} = route.params

 const [shouldShow, setShouldShow] = useState(shouldShowValue);

 return (
  {shouldShow ? <Button> Yayy this button appears now <Button /> : null}
  )
 }
}

'''

this is just pseudo code and not at all 
like the code I have written, 
but its just meant as an example to get a 
understanding of what I mean.

(updateParams) isnt a function that exists, 
but I want something similiar like it. 
Is there a way of updating the params in a 
component from another component without having 
to navigate there? Like with 
navigate.navigate("address" {params go here}) 
but without the navigation part?
ogsagwnx

ogsagwnx1#

你可以考虑使用useContext()钩子来执行你的功能。使用导航库来传递参数而不导航到那个页面是某种误用导航函数。
通过useContext,可以在组件之间共享状态,如果你想在点击action时改变值,也可以把useState钩子传递给useContext,或者考虑使用redux库来共享状态。

import { useState, createContext, useContext } from 'react';

const shareContext = createContext(null);

export default function demoUseContext() {
    const [isClicked, setClicked] = useState(false);
    return (
      <shareContext.Provider value={{isClicked, setClicked}}>
        <ComponentA />
        <ComponentB />
      </shareContext.Provider>
    )
  }
  
  function ComponentA() {
    const sharedParam = useContext(shareContext);
    return (
        <button onClick={() => sharedParam.setClicked(!sharedParam.isClicked)}>
            click to change value
        </button>
    );
  }
  
  function ComponentB() {
    const sharedParam = useContext(shareContext);
    return (
        sharedParam.isClicked && <div>it is clicked</div>
    )
  }

如上例所示,代码将父组件的useState挂钩传递到上下文,其中A使用上下文的useState通过setClicked设置isClicked,B使用上下文的值isClicked
你也可以设法设置上下文,不仅在钩子中有值,而且在参数/对象/函数中有值作为回调。
有关详细信息,请参阅https://reactjs.org/docs/hooks-reference.html#usecontext。有多个钩子,包括useContext fyi

nhjlsmyf

nhjlsmyf2#

将参数传递给路由有两个部分:
将params作为navigation.navigate函数的第二个参数放入一个对象中,从而将params传递给路线:navigation. navigation('路线名称',{ /* 参数转到此处 */ })
读取屏幕组件中的参数:route.params.
我们建议您传递的参数是JSON可序列化的,这样,您就可以使用状态持久化,并且您的屏幕组件将拥有实现深度链接的正确契约。

相关问题