2017-03-22 43 views
1
import { Component } from 'react' 

export default class Overlay extends Component { 

    static propTypes = { 
     show: React.PropTypes.bool 
    }; 

    constructor(props, context) { 
     super(props); 
    } 

    render() { 
     const { show } = this.props; 
     return (
      <div id="overlay"> 
        {show && 
         this.props.children 
        } 
      </div> 
     ) 
    } 
} 

上記は私のオーバーレイ成分です。リアクションについてもっと理解したいので、私はどのプレミード成分もnpmから使用しないようにしています。子供がレンダリングされた後、私は何かをすることができますか?反応成分/オーバーレイ反応成分で反応成分DidMountを使用する

他のコンポーネントのどこかで、私は<Overlay show={true} />を実行します。今、子供がレンダリングされた後に何かしたいです。ユーザーがオーバーレイをトリガーした後ではじめてトリガーしますが、オーバーレイコンポーネントではトリガーしませんでした。

答えて

2

componentWillReceivePropsライフサイクルメソッドを使用できます。これはコンポーネントに送信される「新しい」小道具を受け取り、変更があるかどうかを確認できます。コンポーネントが変更されたときにいつでも呼び出されることが保証されていますが、変更されていない場合は呼び出される可能性がありますので、興味のあるプロップが変更されているかどうかを手動で確認する必要があります。

(あなたはそこに何もしていない場合にも、コンストラクタを削除することができます)

import { Component } from 'react' 

export default class Overlay extends Component { 

    static propTypes = { 
     show: React.PropTypes.bool 
    }; 

    componentDidMount() { 
     console.log("The componentDidMount method is only fired the first time the component is mounted"); 

    componentWillReceiveProps(nextProps) { 
     // this will run every time the props change - and possibly in addition to this, so we need to check for prop changes 
     if (this.props.show !== nextProps.show) { 
      console.log("The show prop changed!); 
     } 
    } 

    render() { 
     const { show } = this.props; 
     return (
      <div id="overlay"> 
        {show && 
         this.props.children 
        } 
      </div> 
     ) 
    } 
} 
+0

、これは動作しませんなぜ任意の手掛かり? 'document.getElementsByTagName( 'body')。style ['background'] = 'red'; ' – Mellisa

+1

getElementsByTagNameメソッドは、要素のコレクションを返します。したがって、返される内容にスタイルを直接設定することはできません。 ([MDN Docs](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName)は、関数を検索するための素晴らしいリソースです)。私はこれに別の方法でアプローチします... 1)赤い背景のCSSクラスを作成します。 '.overlay-background {背景色:赤; } '2)' document.body.classList.add( 'overlay-background'); 'を使用します。 –