![](/img/trans.png)
[英]Can not get correct clientWidth or clientHeight with react ref
[英]How to get correct width of element with ref in react componentDidUpdate
我正在嘗試在表中添加凍結列(具有固定的類名)。 我的目標是將左 css 屬性添加到 header 元素。 Left 屬性將從之前的 header 元素的寬度計算。 我正在渲染中收集標題參考。 在 componentDidUpdate 中,將 left 屬性設置為 header 元素。 使用 getBoundingClientRect 獲取寬度,它給了我錯誤的寬度(通常:124px - 得到 91px)。 我怎樣才能得到正確的寬度?
componentDidUpdate(prevProps, prevState) {
let totalWidth = 0
this._headers.map(header => {
let header1 = ReactDOM.findDOMNode(header).getBoundingClientRect()
let thDom = ReactDOM.findDOMNode(header)
if(thDom.className.includes('fixed')) {
thDom.style.left = `${totalWidth}px`
}
totalWidth += header1.width
})
}
在 componentDidMount 中添加 document.body.onload = this.onLoad 並在 onLoad function 中進行所有計算解決了 mu 問題。
componentDidMount() {
document.body.onload = this.onLoad
}
onLoad() {
let totalWidth = 0
this._headers.map(header => {
let header1 = ReactDOM.findDOMNode(header).getBoundingClientRect()
let thDom = ReactDOM.findDOMNode(header)
if(thDom.className.includes('fixed')) {
thDom.style.left = `${totalWidth}px`
}
totalWidth += header1.width
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.