2016-08-15 94 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); 
},