2016-11-11 11 views
0

ChildコンポーネントはBaseComponentsetTitleメソッドを呼び出すことができます。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を実行することは可能ですか?

答えて

1

継承を避ける必要があります。あなたが言ったように、HOCが...あなたの情報について 移動するための方法である、あなたはスーパーで親クラスを呼び出すことができます。

興味深い
class Child extends BaseComponent{ 

    componentDidMount() { 
     super.componentDidMount(); // Call the parent class 
     this.setTitle(); 
     console.log('child componentDidMount') 
    } 

    render() { 
     return <div>react is awesome</div> 
    } 
} 
+0

〜私もこのコード 'React.Component.prototype.setTitle'を作ります。 'super.someMethod'を呼び出す方法ではありません(毎回呼び出す必要はないので、すべての子クラス' componentDidMount'が実行されるときに常に実行したい)、内部的に子 'componentDidMount'で自動的に行いますか? – novaline

関連する問題