繁体   English   中英

从父组件中的子组件获取数据

[英]Get data from child component in react in parent

我有一个基本组件,其渲染功能如下所示

    <QuestionsDrawer open={this.state.drawerOpen} onClose={this._toggleDrawer}>
      <Search />
      <QuestionList
        questions={this.state.rowData}
        selected={[]}
        ref={ref => (this.listItem = ref)}
      />
    </QuestionsDrawer>

关闭抽屉后,将this._toggleDrawer函数。

_toggleDrawer = () => {
  console.log("selected", this.listItem._fetchSelected());
  this.setState(prevState => ({
    drawerOpen: !prevState.drawerOpen,
  }));
};

发生这种情况时,我想从QuestionList组件中获取数据。 我已经尝试过refs但是却Cannot read property '_fetchSelected' of undefined错误的Cannot read property '_fetchSelected' of undefined

这就是QuestionList组件中的函数的样子

_fetchSelected = () => {
  return this.state.selected;
};

这里出了什么问题,有没有更好的方法来实现呢?

您可以在Parent组件中创建一个方法,然后通过props将其传递给子组件。 该方法可以接受一个参数,该参数是您从子组件中发送this.state.selected 然后,您的父组件将从该方法访问此数据。

我在下面对代码进行了快速可视化,希望您能理解。

// Callback function in the parent that gets passed
// by props to QuestionList

const questionListCallback = (dataFromQuestionList) => {
  // Do something with the data from QuestionList here
}

<QuestionsDrawer open={this.state.drawerOpen} onClose={this._toggleDrawer}>
  <Search />
  <QuestionList
    questions={this.state.rowData}
    drawerOpen={this.state.drawerOpen}
    callbackFromParent={this.questionListCallback}
    selected={[]}
    ref={ref => (this.listItem = ref)}
  />
</QuestionsDrawer>


// Below is for the QuestionList component
// If you for example want to grab the data in componentDidUpdate

componentDidUpdate(prevProps, prevState) {
  // Do something to get the data here and store it somewhere
  // Maybe in the state in the child?
  if (!this.props.drawerOpen && prevState.data !== this.state.data) {
    this.setState({ data: data}, () =>{
      callbackFromParent(data);
    })
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM