依賴內(nèi)層DOMsize設定外層DOM的size

遇到的問題

在應用scrollPane組件包裹tree組件的時候,由于flex布局,內(nèi)層組件超出部分不會自動超出外層父組件,這時候需要手動去設置內(nèi)層組件的size。

一開始,想當然在tree組件componentDidMount中根據(jù)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,再根據(jù)獲取的數(shù)據(jù)進行后續(xù)操作。

關鍵代碼如下:

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...
}

個人經(jīng)驗,歡迎指正。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • 作為一個合格的開發(fā)者,不要只滿足于編寫了可以運行的代碼。而要了解代碼背后的工作原理;不要只滿足于自己的程序...
    六個周閱讀 8,524評論 1 33
  • 前端開發(fā)面試題 面試題目: 根據(jù)你的等級和職位的變化,入門級到專家級,廣度和深度都會有所增加。 題目類型: 理論知...
    怡寶丶閱讀 2,609評論 0 7
  • 謝謝作者的文章 非常喜歡 請允許收藏! 博客園首頁博問閃存新隨筆訂閱管理 vue之better-scroll的封裝...
    peng凱閱讀 16,567評論 2 5
  • 40、React 什么是React?React 是一個用于構建用戶界面的框架(采用的是MVC模式):集中處理VIE...
    萌妹撒閱讀 1,052評論 0 1
  • 原教程內(nèi)容詳見精益 React 學習指南,這只是我在學習過程中的一些閱讀筆記,個人覺得該教程講解深入淺出,比目前大...
    leonaxiong閱讀 2,860評論 1 18