gpt4 book ai didi

javascript - 无法在 React 中获得真实的元素高度

转载 作者:行者123 更新时间:2023-11-30 15:03:32 33 4
gpt4 key购买 nike

我需要将文本分成两行。我有 React 组件,但我无法获得更新的高度 - 只有元素呈现后的高度。这是我的组件

  constructor (props) {
super(props)

this.state = {
text: props.text
}
}

componentDidMount() {
let element = ReactDOM.findDOMNode(this)
let parent = element.parentNode
let originalText = element.innerText
let containerHeight = parent.offsetHeight
let temp = originalText
if (containerHeight < element.offsetHeight) {
while(containerHeight < ReactDOM.findDOMNode(this).offsetHeight) {
temp = temp.substr(0, temp.length-1)
this.setState({
text: temp
})
i++
console.log(temp,containerHeight,ReactDOM.findDOMNode(this).offsetHeight);
}

temp = temp.substr(0, temp.length-4) + '...'

this.setState({
text: temp
})
}
}


render() {
return (
<span>
{this.state.text}
</span>
)
}

如何在每次重新渲染后获取元素高度?

PS 我发现了问题:

我应该在这里使用 componentDidUpdate() 而我不需要在 componentDidUpdate() 方法中使用 while,因为它会在我每次更新状态时触发。

最佳答案

您注册了触发器 componentDidMount。您还应该注册 componentDidUpdate

查看此文档以了解 React 中的生命周期:

https://busypeoples.github.io/post/react-component-lifecycle/

关于javascript - 无法在 React 中获得真实的元素高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140446/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com