javascript - 一组组件在reactjs中挂载后如何执行功能?

标签 javascript reactjs react-dom

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/

相关文章:

javascript - jquery 选择器中包含+startswith

javascript - 变量范围: Global variable inside function

javascript - react : Element is changing a controlled input of type text to be uncontrolled

javascript - 计算 angularjs 中未决的 $q promise

javascript - 在 Jquery 中加载图层

reactjs - 渲染不同组件 (`BrowserRouter` ) 时无法更新组件 (`Login` )

javascript - 在按钮单击事件上渲染 React 组件

javascript - react : map is not a function

javascript - 为什么开发模式下的 ReactJS 包大小比生产模式小?

javascript - 如何从 axios promise 获取控制台日志