2017-03-22 3 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> 
     ) 
    } 
} 

위는 내 오버레이 구성 요소입니다. 아이들이 렌더링 된 후에 어떻게해야합니까?모달/오버레이 반응 구성 요소에 반응 구성 요소 IDmount 사용

다른 구성 요소의 어느 곳에서 나는 <Overlay show={true} />을 수행합니다. 이제 아이들이 렌더링 된 후에 무언가를하고 싶습니다. 시도했는데 오버레이 구성 요소에

componentDidMount(){ 
    console.log('hey'); 
} 

이 포함되어 있지만 처음 트리거되지만 사용자가 오버레이를 트리거 한 후에는 트리거하지 않습니다.

답변

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 {background-color : red; }'2)'document.body.classList.add ('overlay-background');를 사용하십시오. –

관련 문제