遇到的問題
在應用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...
}
個人經驗,歡迎指正。