2017-11-15 2 views
0

이 반응 할 때 componentDidMount에서 offsetTop 요소를 가져올 때 componentDidUpdate()에서 호출 할 때 같은 요소의 offsetTop 값과 다릅니다. 왜 그런가요? 나는 DOM 요소가 페이지에 배치되므로 offsetTop 값이 정확해야하므로 componentDidMount가 렌더링 후에 호출되었다고 생각했습니다.반응 요소 받기 offsetTop

class Index extends React.Component { 
    ... 
    render() { 
     return (
      <div className="site-wrapper"> 
       <TopHeader /> 
       <IntroSection /> 
      </div> 
     ); 
    } 
} 


class TopHeader extends React.Component { 
    ... 
    componentDidMount() { 
     var rect = ReactDOM.findDOMNode(this).offsetTop; 
     console.log(rect); 
    } 
} 


class IntroSection extends React.Component { 
    ... 
    componentDidMount() { 
     var rect = ReactDOM.findDOMNode(this).offsetTop; 
     console.log(rect); 
    } 
} 

답변

1

componentDidMount은 한 번만 호출됩니다. 그러나 componentDidUpdate은 상태 또는 소품을 통해서도 구성 요소가받은 각 업데이트마다 호출됩니다.

그런 다음 두 라이프 사이클 메소드에서 offsetTop을 구성 요소 상태로 유지하는 것이 좋습니다.

+0

예, 오버 헤드를 줄이기 위해 오버 타임을 변경하지 않기 때문에 각 요소의 offsetTop을 'componentDidUpdate'에 포함시킬 수 있기를 기대했습니다. – ArmenB