2016-08-15 100 views
8

我被告知參考文獻可能會被棄用。獲取元素參考而不使用反應中的參考

我怎能實現以下,考慮到這代碼:

export default class DemoAxis extends Component { 
    componentDidMount() { 
     const el = this.refs.line; 

     const dimensions = .getDimensionsFromElement(el); 
    } 

    render() { 
     return (
     <div ref="line"> 
     </div> 
    ); 
    } 

我需要行格的引用,從它那裏得到的尺寸。

我知道有一個ref回調,我應該使用它嗎?

+0

@MarcoScabbiolo https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute –

回答

8

只有string refs考慮棄用,你仍然可以使用callback refs

export default class DemoAxis extends Component { 
    componentDidMount() { 
     const dimensions = .getDimensionsFromElement(this._line); 
    } 

    render() { 
     return (
     <div ref={ (ref) => this._input = ref }> 
     </div> 
    ); 
    } 
} 

或者在你的情況,你不需要裁判,只是得到從組件this的DOM節點,使用ReactDOM.findDOMNodedemo):

componentDidMount() { 
    const dimensions = ReactDOM.findDOMNode(this).getBoundingClientRect(); 
    console.log(dimensions); 
},