繁体   English   中英

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

[英]React-native - passing values between components

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

我只是将其设置为非常简单即可进行测试。 启动应用程序时,我打开了一个索引文件。 在索引中,我在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>
        );
    }
}

暂无
暂无

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

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