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

标签 javascript reactjs react-native

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

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

相关文章:

reactjs - 在Vue中如何区分同名的prop和方法?

reactjs - 如何使 React js Material-UI 表具有响应性并使其具有相等的列间距?

javascript - 无法显示更新状态(REACT-NATIVE)

javascript - 从 firebase 获取数据后刷新选择器项目

ios - requiresMainQueueSetup 和 dispatch_get_main_queue 的区别?

javascript - VueJS 如何从方法而不是模板中监听事件

javascript - 更改蓝图多选输入占位符文本

javascript - Node.js:JSDOM 删除内联事件

reactjs - 如何在 Enzyme React 测试中访问嵌套组件

javascript - array.push() 变量结构不同?