渲染后获取React.refs DOM节点宽度,并仅在宽度值已更改时触发重新渲染

时间:2016-02-18 22:40:26

标签: javascript reactjs

我正在尝试获取state DOM元素的宽度并设置render,然后在组件setState中使用。之所以出现此问题,是因为此宽度会因用户输入而发生变化,当我在componentDidUpdate内尝试setState: refs.element.clientWidth时,它会启动无限循环并且我的浏览器会发生炸弹。

我在这里创建了一个小提琴http://jsbin.com/dizomohaso/1/edit?js,output(打开控制台获取一些信息)

我的想法是;

  • 组件装载,render

  • 用户输入数据,触发shouldComponentUpdate

  • 仅当true 等于new.state时,
  • old.state才会返回state。我的问题是,我不确定更新此let f = function () { return `Hello ${this.name}!` } f.bind({ name: 'Stackoverflow-User' })(); // Hello Stackoverflow-User! 哪个有意义?

非常感谢任何帮助,感谢阅读!

布拉德。

1 个答案:

答案 0 :(得分:20)

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,因为根据您的浏览器,该元素可能具有小数宽度,并且该宽度将返回而不进行任何舍入。

相关问题