如何在本机屏幕之间传递数据? [英] How to pass data between react native screens?
问题描述
嘿,我是新来的本地人.因此,基本上,我有一个带有两个屏幕选项的堆栈导航器:屏幕1(默认)和屏幕2.我已经设置了一个按钮,以便在按下该按钮时将带我到屏幕2.所以在Screen1中,我有一个数组显示为scrollview组件.现在,当我按下按钮转到screen2时,我想将一些数组值传递给该screen2组件.最好的方法是什么?谢谢:)
Hey I am new to react native. So basically I have a stack navigator with two screen option: Screen 1 (Default) and Screen2. I already set up a button so that when pressed it will take me to Screen 2. So in Screen1 I have an array displayed as scrollview component. Now when i press the button to go to screen2 I want to pass some of the array values to that screen2 component. What is the best way to do it? Thank you :)
我真的很新,所以我的尝试有点愚蠢.我尝试导入Screen1组件并通过this.state调用数组值,但是没有访问权限.
I am really new so my attempts are kinda dumb. I tried importing the Screen1 component and calling the array values via this.state but no access.
推荐答案
传递数据的最简单方法是在导航时.为此,最好将阵列置于状态,然后使用以下方法:
The easiest way to pass the data is when you are navigating. To do that it is better that you put your array in a state an then use the following method:
onPress=()=>{
this.props.navigation.navigate('Screen2', {
yourArray: this.state.yourArray, });
}
}
然后在下一个屏幕(Screen2)中可以在props中找到数组(您的数据).因此在scrren2的构造函数中,您可以在此处找到数据:
Then in the next screen(Screen2) you can find the array(your data) in the props.So in your constructor in scrren2 you can find the data here:
constructor(props) {
super(props);
var params = props.navigation.state.params.yourArray;
}
还可以在不触摸状态的情况下返回上一屏幕,您可以在后退"按钮中使用以下代码:
Also to come back to your previous screen without touching your states you can use this code in your back button:
const { goBack } = this.props.navigation;
goBack();
这篇关于如何在本机屏幕之间传递数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!