2017-03-28 2 views
1

저는 React에 매우 익숙합니다. 요소의 높이를 가져와야하므로 componentDidMount 메서드에서 가져 오려고합니다. 이 메소드는 컴포넌트를 렌더링 한 후에 호출 된 것으로 이해합니다.이 컴포넌트는 마지막에 실제 DOM을 작성하는 것으로 가정합니다. 그러나 최종 DOM을 사용하려면 먼저 componentDidMount이 호출되어야합니다. 어째서?실제 DOM을 사용하기 전에 componentDidMount가 호출됩니다.

componentDidMount() { 
    const el = window.document.getElementById('comments'); // el is null 
    console.log(el); 
} 

resize() { 
    const el = window.document.getElementById('comments'); // el is null 
    console.log(el); 
} 

render() { 
    const { name } = this.props; 
    const Comments = this.props.comments.filter(comment => comment.body !== null && comment.body !== '').map(comment => <Comment key={comment.id} comment={comment} />); 
    return (
    <div ref={this.resize}> 
     <div> 
     <div id="comments"> 
      { Comments } 
     </div> 
     </div> 
    </div> 
); 
} 
+0

코드 예제를 추가하십시오. –

+0

@RuiCosta 완료 및 감사 – R01010010

답변

1

그렇다면 실제로 렌더링 방법으로 반환되는 DOM에 의존해서는 안됩니다. 구성 요소와 렌더링 부분은 React에서 2 가지 다른 프로세스이므로 외부에서의 접근 방식은 React에서 작동하지 않습니다.

componentDidMount() { 
     var erd = elementResizeDetectorMaker(); 
     erd.listenTo(this.refs.comments, resize); 
    } 

    resize(element) { 
     //do-some-thing 
    } 

    render() { 
     const { name } = this.props; 
     const Comments = this.props.comments.filter(comment => comment.body !== null && comment.body !== '').map(comment => <Comment key={comment.id} comment={comment} />); 
     return (
     <div> 
      <div> 
      <div ref={comments => { this.comments = comments; }}> 
       { Comments } 
      </div> 
      </div> 
     </div> 
    ); 

} 

PS : 당신이 할 수있는 것은 심판으로 의견을 저장할 수있다 나는이 놀라운 라이브러리를 사용하는 비슷한 상황에서 : https://github.com/wnr/element-resize-detector

+1

고마워,하지만 난 여전히 그 사건에 요소의 실제 높이가 없어 – R01010010

+1

[String refs] (https://facebook.github.io/react/docs/refs-and-the -dom.html # legacy-api-string-refs)는 기존 코드로 간주되므로 새 코드에서는 피해야합니다. 'ref = {comments => {this.comments = comments; }}'. –

0

당신의 선택 const el = window.document.getElementById('comments'); (이 안티 패턴) 가 null 당신 때문에 componentDidiMount 렌더링 라이프 사이클에 노드가 존재하지 않습니다를 선택하십시오.

노드의 내부 React 패턴 (또는 그림자 DOM)을 선택해야합니다.

이 코드 블록의 코드를 변경하고 javascript selector 'getElementBy'를 React의 참조로 대체하십시오. 설명서 확인 https://facebook.github.io/react/docs/refs-and-the-dom.html

componentDidMount() { 
    let el = this.refs['comments'] 
    console.log(el.clientHeight) 
    this.resize() 
} 

resize() { 
    let el = this.refs['comments'] 
    console.log(el.clientHeight) 
} 

render() { 
    const { name } = this.props; 
    const Comments = this.props.comments.filter(comment => comment.body !== null && comment.body !== '').map(comment => <Comment key={comment.id} comment={comment} />); 
    return (
    <div ref='comments'> 
     <div> 
     <div id="comments"> 
      { Comments } 
     </div> 
     </div> 
    </div> 
); 
} 
관련 문제