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

Bra*_*rad 9 javascript reactjs

我试图获取refDOM元素的宽度,state然后设置为在Component中使用render.问题出现是因为这个宽度在用户输入上发生变化,当我setStatecomponentDidUpdate其中尝试时,它会启动无限循环并且我的浏览器会发生炸弹.

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

我的想法是;

  • 组件安装座, setState: refs.element.clientWidth

  • 用户输入数据,触发器 render

  • shouldComponentUpdate返回true只要new.state相等old.state.我的问题是,我不确定更新这个有意义state吗?

任何帮助将不胜感激,感谢阅读!

布拉德.

Dav*_*vid 21

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

  }

})
Run Code Online (Sandbox Code Playgroud)

我喜欢使用,.getBoundingClientRect().width因为根据您的浏览器,元素可能具有小数宽度,并且该宽度将返回而不进行任何舍入.

  • 我假设您定义了`node`参考。它可能不是HTML元素,而是容器或react组件。https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect获取所需的HTML元素并获取其宽度。 (3认同)