簡體   English   中英

如何在 react componentDidUpdate 中使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM