简体   繁体   中英

How to get correct width of element with ref in react componentDidUpdate

I am trying to add frozen columns in table (with fixed className). My aim is add left css property to header elements. Left property will calculate from previous header element's width. I am collecting headers ref in render. In componentDidUpdate set the left property to header element. Getting width with getBoundingClientRect and it gives me wrong width (normally: 124px - getting 91px). How can I get correct width?

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

我的标题计算值

下一个标题从前一个标题的宽度计算左属性

Adding document.body.onload = this.onLoad in componentDidMount and doing all calculations in onLoad function solved mu issue.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM