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

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

你可能感兴趣的:(前端,js,react)