2016-09-17 15 views
2

コールバックcomponentDidMountは、そのコンポーネントの要素を処理しているときには完全に機能しますが、コンポーネントのグループがマウントされた後、ページ上の複数のコンポーネントの要素を処理する関数を実行します。私ができることは何ですか?グループコンポーネントをreactjsでマウントした後に関数を実行するにはどうすればよいですか?

+0

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

子供のようなものを持っているでしょう。実際にアプリケーションの中に広がる実装条件に基づいてイベントをトリガする必要があります**あなたが実際にしようとしていることは何ですか? – gravityplanx

答えて

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() 
} 
0

は、あなたは彼らのために関数を定義し、それらをインスタンス化refを割り当てることができます。そして、親がその機能を実行することができます:あなたはアンチパターンを作成しようとしているようにこれはそう

... 
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; 
}, 
... 
+0

これは、OPが何を記述しているかを達成するための1つの方法であり、@ erik-snの答えも非常に良い選択肢であると付け加えます –

関連する問題