首页 > 解决方案 > 从父组件获取子组件 Prop

问题描述

我正在使用以下 React Native 模块: https ://github.com/shariqahmed1/react-native-animated-tree-view

我喜欢从 TreeView 中获取点击的项目。

文档说我应该能够通过onClick prop. 在此处输入图像描述

我的尝试是这样的:

<TreeView
 onPress={() => console.log(props.onClick)} //Cannot get clicked item
 data={data} //Works Okay
/>

我能够成功提供源数据,但无法从树视图中获取单击的项目。

如何从父组件获取子组件值?

标签: javascriptreact-native

解决方案


你可以使用Ref/createRef给它一个唯一的引用(就像 ID 一样),然后你就可以访问它了:

 class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

在 onclick 事件处理程序中,使用this.onClickthis.onClick()代替props.onClick()和,您可以使用 this.textInput 访问子组件。当前访问子组件。


推荐阅读