2016-02-18 12 views
5

ref DOM öğesinin genişliğini almayı deniyorum ve render Bileşeninde kullanmak için state'u ayarlayın. Sorun, bu genişlik kullanıcı girdisinde değiştiği için ve componentDidUpdate içinde setState'u denediğimde, sonsuz bir döngü ve tarayıcılarım bombalarım başladığında ortaya çıkar.React.refs DOM düğüm genişliğini oluşturduktan sonra yeniden oluştur ve yalnızca genişlik değeri değiştiyse yeniden oluşturmayı başlat

Burada bir keman http://jsbin.com/dizomohaso/1/edit?js,output (bazı bilgiler konsolu açın) oluşturuldu

Benim düşünce vardı;

  • Bileşen bağlar, setState: refs.element.clientWidth

  • Kullanıcı giriş verileri new.stateeşit değildirold.state için yalnızca render

  • shouldComponentUpdate döner true tetikler. Benim sorunum, bu state'u güncellemenin mantıklı olduğunu bilmiyor muyum?

Okuma için teşekkürler, herhangi bir yardım çok takdir edilecektir!

Brad.

cevap

15
var component = React.createClass({ 

    componentDidMount: function() { 

    //Get initial width. Obviously, this will trigger a render, 
    //but nothing will change, look wise. 
    //But, if this is against personal taste then store this property 
    //in a different way 
    //But it'll complicate your determineWidth logic a bit.   

    this.setState({ 
     elWidth: ReactDOM.findDOMNode(this.refs.the_input).getBoundingClientRect().width 
    }) 
    }, 

    determineWidth: function() { 

    var elWidth = ReactDOM.findDOMNode(this.refs.the_input).getBoundingClientRect().width 

    if (this.state.elWidth && this.state.elWidth !== elWidth) { 

     this.setState({ 
     elWidth: elWidth 
     }) 

    } 

    }, 

    render: function() { 

    var styleProp = {} 

    if (this.state.elWidth) { 
     styleProp.style = { width: this.state.elWidth }; 
    } 

    return (
     <input ref="the_input" onChange={this.determineWidth} {...styleProp} /> 
    ) 

    } 

}) 

Ben tarayıcınıza bağlı olarak eleman kesirli genişliğe sahip olabilir, çünkü .getBoundingClientRect().width kullanmak ister ve bu genişlik herhangi yuvarlanması olmadan dönecektir.

İlgili konular