2

当我处理该组件中的元素时,回调componentDidMount工作得很好,但是我想在安装一组组件后执行一个处理页面上多个组件的元素的函数。我能做到这一点的最好方法是什么?

4

2 回答 2

1

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()
}
于 2016-09-17T19:22:03.087 回答
0

如果其他组件都是子组件,您可以为它们定义一个函数并ref在实例化时为其分配一个。然后父母可以执行该功能:

...
componentDidMount: function() {
  var ret = true;
  var refs = this.refs;
  for (var ref in refs) {
    if (refs.hasOwnProperty(ref)) {
      ret = refs[ref].isValid().success && ret;
    }
  }
  return ret;
},
render: function() {
  return (
    <div>
      <ChildComponent ref="something" />
      <ChildComponent ref="somethingElse" />
    </div> 
 );
}

孩子会有类似的东西:

...
isValid: function() {
  // this is just an example; i don't know what you want your children to return or do...
  ret = true;
  if (<you conditions here>) {
    ret = false;
  }
  return ret;
},
...
于 2016-09-17T19:52:48.843 回答