React获取Dom高度

最近这个React的问题困惑了我几天,总结下React获取Dom 高度
React可以正常获取内容为文字的元素高度,但如果要获取img元素的高度,必须对Img设置固定的高度才可以获取,否则img的高度始终是0;

  1. 在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>
   </>
 );
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值