2016-02-18 9 views
5

ref DOMエレメントの幅を取得しようとしていて、stateをコンポーネントrender内で使用するように設定しようとしています。問題は、この幅がユーザの入力に応じて変化し、setStatecomponentDidUpdate以内に入力すると無限ループを開始し、ブラウザが爆発するためです。React.refsレンダリング後のDOMノードの幅と幅が値が変更された場合にのみ再レンダリングをトリガー

私はここにフィドルhttp://jsbin.com/dizomohaso/1/edit?js,output(いくつかの情報のためのコンソールを開く)を作成し

私の考えていました。

  • コンポーネントマウントを、setState: refs.element.clientWidth

  • ユーザ入力データは、new.state等しくないold.stateである場合にのみrender

  • shouldComponentUpdate戻りtrueをトリガします。私の問題は、このstateをどこで更新すればいいのか分かりません。

お読みいただきありがとうございます。

ブラッド。

答えて

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} /> 
    ) 

    } 

}) 

私は、ブラウザによっては、要素が分数の幅を持っている可能性があるため、.getBoundingClientRect().widthを使用するように、その幅は丸めずに返されます。

関連する問題