gpt4 book ai didi

javascript - React-native - 在组件之间传递值

转载 作者:行者123 更新时间:2023-12-03 01:59:57 24 4
gpt4 key购买 nike

我知道有很多类似的线程,但由于我很难理解答案,所以我想我可以尝试使用自己的代码,看看我是否能理解答案。

我只是将其设置得非常简单来测试一下。我有一个索引文件,在启动应用程序时打开。在索引中,我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com