2016-08-15 13 views
8

में रेफ का उपयोग किए बिना तत्व संदर्भ प्राप्त करें मुझे बताया गया है कि रेफरी को बहिष्कृत होने की संभावना है।प्रतिक्रिया

मैं निम्नलिखित कैसे तो प्राप्त कर सकते थे, इस कोड पर विचार:

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

     const dimensions = .getDimensionsFromElement(el); 
    } 

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

मैं लाइन div के लिए एक संदर्भ की जरूरत है इसे से आयाम मिलता है।

मुझे पता है कि एक रेफ कॉलबैक है, क्या मुझे इसका उपयोग करना चाहिए?

+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> 
    ); 
    } 
} 

या अपने मामले में, आप ReactDOM.findDOMNode का उपयोग कर, एक रेफरी की जरूरत नहीं है, बस घटक this से डोम नोड मिल (demo):

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