のcomponentWillMountを呼び出します。親コンポーネントのcomponentWillMountメソッドをどう呼びますか?Reactjsは、私は以下のように2つのコンポーネントを持つ親コンポーネント
おかげ
のcomponentWillMountを呼び出します。親コンポーネントのcomponentWillMountメソッドをどう呼びますか?Reactjsは、私は以下のように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();
あなたがフォローの方法で親のメソッドを呼び出すことができます。
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>
}
}
私は誤植があると思います: 'super()'は 'Parent'のコンストラクタを呼び出します。同じメソッドではありません。 –
内部で呼び出す必要がある場合は、なぜあなたは親のcomponentWillMountにアクセスする必要がありますか?リアクションのレンダリングツリーに基づいて、子コンポーネントが再びレンダリングされる場合、親を再レンダリングする必要はありません – Robsonsjre
Reactコンポーネントでこのような継承を行わないことをお勧めします。理論的には 'super.componentWillMount()'と呼ぶことができますが、それは良いことではありません。 https://twitter.com/dan_abramov/status/571278443712794625?lang=en –