0
Child
コンポーネントはBaseComponent
setTitle
メソッドを呼び出すことができます。React、子クラスが継承してマウントされたとき、親クラスはライフサイクルメソッドを実行しますか?
ただし、Child
コンポーネントを搭載した場合、BaseComponent
'ライフサイクルメソッドcomponentDidMount
は実行されません。
class BaseComponent extends React.Component{
componentDidMount() {
console.log('baseComponent componentDidMount')
}
setTitle(title) {
document.title = title || 'default title'
}
}
class Child extends BaseComponent{
constructor() {
super();
}
componentDidMount() {
this.setTitle();
console.log('child componentDidMount')
}
render() {
return <div>react is awesome</div>
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
私も多分HOC
がよりよい解決策を知っています。 es5
を使用する場合は、mixins
が最適です。 しかしそれは私の質問ではありません。したがって、ライフサイクルメソッドBaseComponent
を実行することは可能ですか?
〜私もこのコード 'React.Component.prototype.setTitle'を作ります。 'super.someMethod'を呼び出す方法ではありません(毎回呼び出す必要はないので、すべての子クラス' componentDidMount'が実行されるときに常に実行したい)、内部的に子 'componentDidMount'で自動的に行いますか? – novaline