2017-10-05 1 views
2

내 getBoundingClientRect는 항상 0 값으로 가득 찬 객체를 반환합니다. 비동기와 관련된 것이 겠지요? 다음은 구성 요소의 너비와 x를 가져 오는 함수의 정의입니다. 여기에 당신은 인라인 심판 대신 심판 콜백을 사용할 필요가 getBoundingClientRectReact get component size

DOMRect {x: 0, y: 0, width: 0, height: 0, top: 0, …} 
bottom : 0 
height : 0 
left : 0 
right : 0 
top : 0 
width : 0 
x : 0 
y : 0 

답변

1

DOM을 실제로 사용할 수있는 및 componentDidMount가 호출되는 일부 finickiness있다

componentDidMount() { 
    window.requestAnimationFrame(() => { 
    this.setState({ 
     left: Math.round(this.container.getBoundingClientRect().width),      
     x: Math.round(this.container.getBoundingClientRect().x)        
    }); 
    }                      
} 

시도; requestAnimationFrame을 사용하면 페인트가 발생한 후에 호출됩니다.

+0

그래, 그 작품 :). 감사 인사 – user2391356

0

의 응답이

render() { 
     const containerStyle = { 
      left : `-${Math.min(this.state.left, this.state.x) - 35}px`,             
     }; 
     return (!!this.state.visible && 
      <div 
       className={styles.container} 
       style={containerStyle}                
       ref={(element) => { this.container = element; }}         
      > 

: 여기

 componentDidMount() { 
     this.setState({ 
      left: Math.round(this.container.getBoundingClientRect().width),      
      x: Math.round(this.container.getBoundingClientRect().x)        
     });                      
    } 

그리고

는 렌더링 함수의 시작입니다. 인라인 심판을 사용하면 첫 번째 렌더 패스가 ref가 null이됩니다. 콜백을 전달할 때 요소가로드 된 후에 만 ​​호출됩니다.

applyRef(ref) { 
    this.container = ref; 
} 
... 
<div 
    className={styles.container} 
    style={containerStyle} 
    ref={this.applyRef} 
> 
관련 문제