依赖内层DOMsize设定外层DOM的size

遇到的问题

在应用scrollPane组件包裹tree组件的时候,由于flex布局,内层组件超出部分不会自动超出外层父组件,这时候需要手动去设置内层组件的size。

一开始,想当然在tree组件componentDidMount中根据tree的scrollWidth,scrollHeight来init tree size。然后在在 componentWillReceiveProps中再次获取 this.refs.tree的scroll size重新设置tree size。或者在componentDidUpdate中获取 this.refs.tree的scroll size重新设置tree size。

bug原因

但是,由于在componentDidMount中init了 tree size,在componentWillReceiveProps和componentDidUpdate中获取this.refs.tree 的scroll size还是第一次设置的大小。这时候我们就会获取不到正确的 scroll size。

解决方法:

在componentWillReceiveProps中取消init的tree size 然后在获取其size,再根据获取的数据进行后续操作。

关键代码如下:

Class Tree extends React.Component {
  constructor(props) {
    //...code...
    this.state = {
      //...code...
      treeWidth: null
      //...code...
    }
    //...code...
  }

  componentDidMount() {
    //...code...
    this._treeWidth = this.refs.tree.scrollWidth;
    this.setState({
        treeWidth: this._treeWidth
    })
    //...code...
  }

  componentWillReceiveProps() {
    //...code...
    this.setState({
        treeWidth: null
    }, () => {
      if(this.refs.tree.scrollWidth !== this._treeWidth) {
        this._treeWidth = this.refs.tree.scrollWidth;
      }

      this.setState({
        treeWidth: this._treeWidth
      })
    })
    //...code...
  }

  render() {
   //...code...
   return (
      <div ref='tree' style={this.state.treeWidth ? {width: `${this.state.treeWidth}px`}} /*...*/>
         //...
      </div>
   )
  }

  //...code...
}

个人经验,欢迎指正。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,526评论 1 33
  • 前端开发面试题 面试题目: 根据你的等级和职位的变化,入门级到专家级,广度和深度都会有所增加。 题目类型: 理论知...
    怡宝丶阅读 2,611评论 0 7
  • 谢谢作者的文章 非常喜欢 请允许收藏! 博客园首页博问闪存新随笔订阅管理 vue之better-scroll的封装...
    peng凯阅读 16,567评论 2 5
  • 40、React 什么是React?React 是一个用于构建用户界面的框架(采用的是MVC模式):集中处理VIE...
    萌妹撒阅读 1,058评论 0 1
  • 原教程内容详见精益 React 学习指南,这只是我在学习过程中的一些阅读笔记,个人觉得该教程讲解深入浅出,比目前大...
    leonaxiong阅读 2,860评论 1 18