javascript - 在父组件中 react 时从子组件获取数据

标签 javascript reactjs ecmascript-6 react-redux ecmascript-2016

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

    <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;
};

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

最佳答案

您可以在父组件中创建一个方法,然后通过 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);
    })
  }
}

关于javascript - 在父组件中 react 时从子组件获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53600090/

相关文章:

javascript - webpack 和 react 识别 css 类名

javascript - 如何增加基于express的node.js应用程序的代码覆盖率?

javascript - wrapAsync 返回函数而不是结果

javascript - 如何在 iPad 上自动打开 HTML 选择菜单

reactjs - React 返回 200 表示未找到页面?

javascript - 迭代 react 组件

javascript - 对对象数组进行排序

javascript - 在跨度之间插入字符串变量

javascript - react : Is it possible to stop code 'reading' until component will receive new props?

reactjs - 将文件从(快速)API 上传到 Azure Blob 存储