我知道有很多类似的线程,但由于我很难理解答案,所以我想我可以尝试使用自己的代码,看看我是否能理解答案。
我只是将其设置得非常简单来测试一下。我有一个索引文件,在启动应用程序时打开。在索引中,我在 this.state 中有 testValue:
更新:
登录:
constructor(props){
super(props);
this.state={
credentials: {
username: "",
password:"",
}
}
this.navigate = this.props.navigation.navigate;
{...}
this.navigate("main", {
credentials: this.state.username,
});
In main:
constructor(props) {
super(props);
this.params = this.props.navigation.state.params;
this.navigate = this.props.navigation.navigate;
{...}
render() {
console.log(this.params.username);
最佳答案
这实际上会记录 testValue。您所要做的就是将 testValue 状态作为 TestIndex 组件中的 prop 传递。像这样:
Index.jsx
export default class Index {
constructor(props) {
super(props);
this.state = {
testValue: 'hello'
}
}
render() {
return <TestIndex testValue={this.state.testValue} />
}
}
TestIndex.jsx
export default class TestIndex extends React.Component {
index() {
this.props.navigation.navigate("index")
}
handleClickMain = () => {
this.props.navigation.navigate("index");
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity style={styles.btn} onPress={() => {
console.log(this.props.testValue) //here's where I want it to log testValue from the index file
this.handleClickIndex()
}
}>
</TouchableOpacity>
</View>
);
}
}
关于javascript - React-native - 在组件之间传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50081175/