最近这个React的问题困惑了我几天,总结下React获取Dom 高度
React可以正常获取内容为文字的元素高度,但如果要获取img元素的高度,必须对Img设置固定的高度才可以获取,否则img的高度始终是0;
- 在componentDidMount中获取
// 只在componentDidMount里获取,组件更新的时候就获取不到了
class PunchCard extends Component{
componentDidMount(){
var box=document.getElementById("toppoint");
if(box){ //此处在加一层判断,更加严密,如果box存在的情况下获取
console.log(box.offsetHeight);
}
}
render() {
return (
<div>
<div id="toppoint">hello</div>
</div>
);
}
}
export default PunchCard;
2.利用ref保存DOM节点,然后读取clientWidth,clientHeight获取宽高参数。
import React, { Component } from 'react';
import 'assets/css/App.css'
export class App extends Component {
constructor(props) {
super(props);
this.saveRef = ref => {this.refDom = ref};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
const {clientWidth, clientHeight} = this.refDom;
console.log('====================================');
console.log(clientWidth, clientHeight, this.refDom);
console.log('====================================');
}
render() {
return (
<div ref={this.saveRef} onClick={this.handleClick} > Loading...</div>
);
}
}
// 没有选择使用 useRef,因为当 ref 是一个对象时它并不会把当前 ref 的值的 变化 通知到我们。使用 callback ref 可以确保 即便子组件延迟显示被测量的节点 (比如为了响应一次点击),我们依然能够在父组件接收到相关的信息,以便更新测量结果。
function MeasureExample() {
const [height, setHeight] = useState(0);
const measuredRef = useCallback(node => {
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
}
}, []);
return (
<>
<h1 ref={measuredRef}>Hello, world</h1>
<h2>The above header is {Math.round(height)}px tall</h2>
</>
);
}