2017-02-07 17 views
0

のcomponentWillMountを呼び出します。親コンポーネントのcomponentWillMountメソッドをどう呼びますか?Reactjsは、私は以下のように2つのコンポーネントを持つ親コンポーネント

おかげ

+0

内部で呼び出す必要がある場合は、なぜあなたは親のcomponentWillMountにアクセスする必要がありますか?リアクションのレンダリングツリーに基づいて、子コンポーネントが再びレンダリングされる場合、親を再レンダリングする必要はありません – Robsonsjre

+1

Reactコンポーネントでこのような継承を行わないことをお勧めします。理論的には 'super.componentWillMount()'と呼ぶことができますが、それは良いことではありません。 https://twitter.com/dan_abramov/status/571278443712794625?lang=en –

答えて

2
 class Child extends Parent 
     { 
     componentWillMount() { 
      super.componentWillMount() ; //parent componentWillMount 
      console.log('child componentWillMount'); 
     } 
     } 

説明:

Child#componentWillMountオーバーライドParent#componentWillMountを。だから、:

  • あなたは、余分なロジックを追加することなくParent#componentWillMountのロジックのみが必要な場合は、ChildからcomponentWillMountを削除することを推奨します。

  • あなたは、いくつかのロジックを追加してParent#componentWillMountを呼び出すChild#componentWillMountを保持し、それsuper.componentWillMount();

0

あなたがフォローの方法で親のメソッドを呼び出すことができます。

class Child extends Perent { 
    componentWillMount() { 
     super(); 

     // Insert your child specific code here 
    } 
} 

しかしBen Nyrberg already mentioned in the commentsとして、それは良い練習ではありません。

反応させ方法に従って、コンポーネント・コードを再利用するのをお勧め成分組成である:

class Parent extends React.Component { 
    componentWillMount() { 
     // Reusable functionality here 
    } 

    render() { 
     return {this.props.children} 
    } 
} 

class Child extends React.Component { 
    componentWillMount() { 
     // Child specific functionality 
    } 

    render() { 
     return <div>Whatever you want</div> 
    } 
} 


class App extends React.Component { 
    render() { 
     return <Parent> 
      <Child /> 
     </Parent> 
    } 
} 
+0

私は誤植があると思います: 'super()'は 'Parent'のコンストラクタを呼び出します。同じメソッドではありません。 –

関連する問題