简体   繁体   English

在 react-native 中更新屏幕之间的参数值

[英]Update parameters value between screens in react-native

in my 2 screens react-native app, I'd like to know which is the best way to do the following:在我的 2 个屏幕 react-native 应用程序中,我想知道执行以下操作的最佳方法是:

In the main screen, a simple Text component shows "Hello" and a button that leads to a screen that shows "Hello" in an input field and a "GoBack" button.在主屏幕中,一个简单的 Text 组件显示“Hello”和一个按钮,该按钮通向一个在输入字段中显示“Hello”的屏幕和一个“GoBack”按钮。

By modifying the input and after pressing the "GoBack" button, I want the Text component in the main screen to be updated with the text previously inserted.通过修改输入并在按下“GoBack”按钮后,我希望主屏幕中的 Text 组件使用先前插入的文本进行更新。

Which is the best approach to do this?执行此操作的最佳方法是什么?

TY in advance提前TY

I found the answer by myself.我自己找到了答案。

First of all, in home screen, declare a useState const like this:首先,在主屏幕中,声明一个 useState 常量,如下所示:

const [text, setText] = useState("Hi all, to be modified");

Then, in the Home Screen Button, we have to pass the "coordinate" to the second screen然后,在主屏幕按钮中,我们必须将“坐标”传递给第二个屏幕

onPress={() => navigation.navigate('SecondScreen',
                {
                    textParam: text
                })}

In the "SecondScreen" we have to:在“SecondScreen”中,我们必须:

1: read the value of the params and set it to a new useState const 1:读取参数的值并将其设置为新的 useState const

const [text, setText] = useState(route.params.textParam);

2: set the InputText 2:设置InputText

 <TextInput defaultValue={text} onChangeText={setText}/>

3: pass the updated value back 3:传回更新后的值

onPress={() => navigation.navigate({
            name: 'Home',
            params: { textParam: text },
            merge: true,
          })}

Finally, in the HomeScreen, we could use useEffect hook in order to update our value最后,在 HomeScreen 中,我们可以使用 useEffect 挂钩来更新我们的值

useEffect(() => {
    if (route.params?.textParam) {
        setText(route.params.textParam);
    }
  }, [route.params?.textParam]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM