遇到的問題
在應(yīng)用scrollPane組件包裹tree組件的時(shí)候,由于flex布局蚪腋,內(nèi)層組件超出部分不會(huì)自動(dòng)超出外層父組件孵淘,這時(shí)候需要手動(dòng)去設(shè)置內(nèi)層組件的size瞧挤。
一開始,想當(dāng)然在tree組件componentDidMount中根據(jù)tree的scrollWidth描焰,scrollHeight來init tree size媳否。然后在在 componentWillReceiveProps中再次獲取 this.refs.tree的scroll size重新設(shè)置tree size【G兀或者在componentDidUpdate中獲取 this.refs.tree的scroll size重新設(shè)置tree size逆日。
bug原因
但是,由于在componentDidMount中init了 tree size萄凤,在componentWillReceiveProps和componentDidUpdate中獲取this.refs.tree 的scroll size還是第一次設(shè)置的大小室抽。這時(shí)候我們就會(huì)獲取不到正確的 scroll size。
解決方法:
在componentWillReceiveProps中取消init的tree size 然后在獲取其size靡努,再根據(jù)獲取的數(shù)據(jù)進(jìn)行后續(xù)操作坪圾。
關(guān)鍵代碼如下:
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...
}
個(gè)人經(jīng)驗(yàn),歡迎指正惑朦。