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

时间:2018-12-03 18:54:19

标签: javascript reactjs ecmascript-6 react-redux ecmascript-7

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

    <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错误。

这就是QuestionList组件中的功能

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

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

1 个答案:

答案 0 :(得分:1)

您可以在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);
    })
  }
}
相关问题