我是靠谱客的博主 彩色夕阳,最近开发中收集的这篇文章主要介绍React componentDidMount 中获取元素高度是准确的吗?答案肯定是有准确的时候也有不准确的时候啊使用ref钩子在componentDidMount 中获取div高度的方法不能准确的一些情况,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

React componentDidMount 中获取高度是准确的吗?

  • `答案肯定是有准确的时候也有不准确的时候啊`
  • 使用ref钩子在componentDidMount 中获取div高度的方法
  • 不能准确的一些情况
    • 子元素是有副作用遍历出来的
    • flex布局一些情况,或者calc计算属性
    • 当然这种情况还有很多,欢迎大家补充
    • 解决方案
      • 1. setTimeout ?
      • 2. 不在componentDidMount中获取?

答案肯定是有准确的时候也有不准确的时候啊

使用ref钩子在componentDidMount 中获取div高度的方法

class App extends React.Component {
state = {
height: 0,
}
componentDidMount() {
this.setState({
height: this.refs.thisDiv.getDOMNode().offsetHeight
}
}
render() {
return <div ref="thisDiv">
<h1>height is {this.state.height}</h1>
</div>;
}
}
class App extends React.Component {
state = {
height: 0,
}
componentDidMount() {
this.setState({
height: this.thisDiv.offsetDiv
}
}
render() {
return <div ref={thisDiv => this.thisDiv = thisDiv}>
<h1>height is {this.state.height}</h1>
</div>;
}
}

不能准确的一些情况

子元素是有副作用遍历出来的

class App extends React.Component {
state = {
height: 0,
data: []
}
componentWillMount () {
setTimeout(() => {
this.setState({
data: [1, 2, 3]
})
}, 300)
}
componentDidMount() {
this.setState({
height: this.thisDiv.offsetDiv
}
}
render() {
const { data, height } = this.state;
return <div ref={thisDiv => this.thisDiv = thisDiv}>
<h1>height is {height}</h1>
{
data.map(value => {
return <p key={value}>{value}</p>
})
}
</div>;
}
}

flex布局一些情况,或者calc计算属性

class App extends React.Component {
state = {
height: 0,
}
componentDidMount() {
this.setState({
height: this.thisDiv.offsetDiv
}
}
render() {
return <div ref={thisDiv => this.thisDiv = thisDiv} class="wrapper">
<h1>height is {this.state.height}</h1>
</div>;
}
}
.wrapper {
height: calc("100% -10px");
}

当然这种情况还有很多,欢迎大家补充

解决方案

1. setTimeout ?

setTimeout(() => {
this.setState({
height: this.thisDiv.offsetDiv
}
}, 10)

2. 不在componentDidMount中获取?


<div ref={thisDiv => {
if(thisDiv) {
this.thisDiv = thisDiv
this.setState...
}
}} ></div>

thanks

最后

以上就是彩色夕阳为你收集整理的React componentDidMount 中获取元素高度是准确的吗?答案肯定是有准确的时候也有不准确的时候啊使用ref钩子在componentDidMount 中获取div高度的方法不能准确的一些情况的全部内容,希望文章能够帮你解决React componentDidMount 中获取元素高度是准确的吗?答案肯定是有准确的时候也有不准确的时候啊使用ref钩子在componentDidMount 中获取div高度的方法不能准确的一些情况所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部