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

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

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

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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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>; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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>; } }

不能准确的一些情况

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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计算属性

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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>; } }
复制代码
1
2
3
4
.wrapper { height: calc("100% -10px"); }

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

解决方案

1. setTimeout ?

复制代码
1
2
3
4
5
6
setTimeout(() => { this.setState({ height: this.thisDiv.offsetDiv } }, 10)

2. 不在componentDidMount中获取?

复制代码
1
2
3
4
5
6
7
8
<div ref={thisDiv => { if(thisDiv) { this.thisDiv = thisDiv this.setState... } }} ></div>

thanks

最后

以上就是彩色夕阳最近收集整理的关于React componentDidMount 中获取元素高度是准确的吗?答案肯定是有准确的时候也有不准确的时候啊使用ref钩子在componentDidMount 中获取div高度的方法不能准确的一些情况的全部内容,更多相关React内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部