【问题标题】:React-native - passing values between componentsReact-native - 在组件之间传递值
【发布时间】:2018-04-28 21:20:30
【问题描述】:

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

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

【问题讨论】:

  • 您没有在传递道具的位置显示代码。显示使用 TestIndex 的渲染方法
  • 我没有通过道具。我怎么做?我只是在 this.state 中拥有它
  • 如果你想让'testValue'成为一个道具,那么当你使用Index中的TestIndex时,你必须做类似<TestIndex testValue={this.state.testValue}>的事情
  • 我是通过按钮以某种方式传递它还是将其粘贴到某个地方?是的,我知道我听起来像个白痴,但我就是无法理解这一点。

标签: javascript reactjs react-native


【解决方案1】:

这实际上会记录 testValue。您所要做的就是将 testValue 状态作为道具传递给 TestIndex 组件。像这样:

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>
        );
    }
}

【讨论】:

  • 我觉得您的回复非常接近,谢谢。虽然我在索引渲染中拥有(很多)更多内容,但当我这样做时,我只是直接转到 TextIndex 文件,而不是点击那里。是否可以在按钮 {} 内返回 或者我应该以某种方式创建类?再次感谢您的评论,我真的以为这次我明白了
猜你喜欢
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 2017-09-04
  • 2021-11-15
  • 2019-02-21
  • 2018-07-08
相关资源
最近更新 更多