【问题标题】:How to get state values of other component in React-Native?如何在 React-Native 中获取其他组件的状态值?
【发布时间】:2019-09-29 12:38:55
【问题描述】:
showConfirmationMessage = () => {
    Alert.alert(
      'Confirmation Message',
      'Proceed?',
      [
        {text: 'BACK', onPress: () => this.setState({ loading: false })},
        {text: 'CONFIRM', onPress: () => this._getTaskData()},
      ],

      {cancelable: false},
    );
  }



_getTaskData = () => {
    console.log(this.component2.getValue());
}

这就是我调用函数的方式。 当我直接调用 _getTaskData() 时,它工作正常。但是,当我像上面那样调用它时(通过确认消息),它给出了错误。

【问题讨论】:

    标签: react-native components state


    【解决方案1】:

    Component2 中编写一个函数来获取您的输入值:

    getValue = () => {
        return this.state.inputValue;
    }
    

    并在Component1 中为您的Component2 设置参考

    <Component2 ref={r => this.component2 = r} />
    

    现在您可以通过 this.component2 参考获取输入值

    this.component2.getValue();
    

    【讨论】:

    • 感谢您的回答。我尝试过这个。但它给出了以下错误。 [未处理的承诺拒绝:TypeError:null 不是对象(评估'_this.component2.getValue')]
    • @SennenDeAlmeida 你在哪里使用this.component2.getValue() ??
    • @SennenDeAlmeida 您没有使用正确的this 来引用component2.getValue()。可能是因为你一定会失去这个上下文。
    • 但是,我刚刚发现只有当我在其他函数之后调用这个函数时才会出现这个错误。当我按下按钮时,它会显示一条确认消息。确认后,它会执行 this.component2.getValue() 函数。但是,给出错误。但是,当我在没有确认消息的情况下直接调用 this.component2.getValue() 时,它工作正常。很困惑为什么会出现这个错误。
    • @SennenDeAlmeida 你所说的“确认信息”是什么意思?
    猜你喜欢
    • 1970-01-01
    • 2023-02-13
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多