【问题标题】:Getting Child Component Prop from the Parent Component从父组件获取子组件 Prop
【发布时间】:2020-05-15 08:42:19
【问题描述】:

我正在使用以下 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
/>

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

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

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    您可以使用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.onClick()而不是props.onClick(),在this.onClick中,您可以使用this.textInput访问子组件。current访问子组件。 p>

    【讨论】:

    • 感谢您的一般回答。我不知道Refs,以后会用到。
    【解决方案2】:

    您应该根据文档使用onClick 代替onPress 来获得点击项:

    onClick={props.onClick} // <-- will call parent component's onClick
    
    // OR
    
    onClick={(item) => props.onClick(item)}  // <-- will call parent component's onClick
    

    要检查控制台,请尝试以下代码:

    onClick={(item) => { console.log(item); }}
    

    【讨论】:

    • 这绝对是我需要的。谢谢。
    • @ilvthsgm,很高兴知道,它有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2021-10-15
    • 2019-05-05
    • 1970-01-01
    相关资源
    最近更新 更多