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



我有一个基本组件,它的渲染函数看起来像这个

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

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

您可以在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);
})
}
}

相关内容

  • 没有找到相关文章

最新更新