Callback componentDidMount
在我处理该组件中的元素时工作得很好,但我想在安装一组组件后执行一个处理页面上多个组件元素的函数。最好的方法是什么?
最佳答案
您可以使用 props
将回调函数传递到每个组件,每个 componentDidMount
方法调用它们的父组件,也就是说,更新该组件状态的计数器。当计数器达到您期望渲染的组件数量时,执行您的函数。
在父组件中:
....
shouldComponentUpdate(nextProps, nextState) {
return nextState.childCount >= 4;
}
incrementChildCount() {
this.setState({ childCount: this.state.childCount + 1 });
}
render() {
return(
<div id="container">
<Child callme={this.incrementChildCount} />
<Child callme={this.incrementChildCount} />
<Child callme={this.incrementChildCount} />
<Child callme={this.incrementChildCount} />
);
}
在子组件中:
componentDidMount() {
this.props.callme()
}
关于javascript - 一组组件在reactjs中挂载后如何执行功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39550383/