React中ref获取元素的宽度、高度,react中如何获得元素宽高

1.定义HTMLParagraphElement类型属性。

pvcDesDom:HTMLParagraphElement

2.componentDidMount中获取高度。

componentDidMount() {
        setTimeout(function () {
            this.setState({
                scrollHeight: this.pvcDesDom.scrollHeight
            })
        }.bind(this))
}

3.元素上追加ref属性。

<p className={'pvd-item-describe ' + (this.state.pvdDesShow ? '' : 'pvd-item-describe-hide')} ref={dom => { this.pvcDesDom = dom }}>data</p>

4.通过this.state.scrollHeight获取高度。

补充Dom的宽高和位置

// 尺寸:
clientWidth  |  clientHeight     元素的内尺寸(width + padding)如果有滚动条,是可视区域高度
scrollWidth  |  scrollHeight      元素滚动内容的总高度
offsetWidth  |  offsetHeight     元素的外尺寸  (width + padding + border)
// 位置:
offsetLeft  |  offsetTop     元素相对于已定位父元素(offsetParent)的偏移量
offsetParent元素是指元素最近的定位(relative,absolute)父元素,可递归上溯,如果没有,返回body元素
ele.getBoundingClientRect()   返回元素的大小及其相对可视区域的位置
如:ele.getBoundingClientRect().left   从视口左端到元素左端边框的距离(不包含外边距)
scrollLeft  |  scrollTop     是指元素滚动条位置,它们是可写的

点赞、关注加收藏,我们一起学前端📚

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React,可以使用Refs来获取元素高度,然后将其传递给父组件,从而动态设置父元素高度。具体实现步骤如下: 1. 在子组件,使用Refs获取元素高度。可以使用React.createRef()来创建Refs对象,然后在子元素的渲染函数Refs绑定到子元素DOM节点上。 ```javascript class ChildComponent extends React.Component { constructor(props) { super(props); this.childRef = React.createRef(); } render() { return ( <div ref={this.childRef}> // 子元素内容 </div> ); } } ``` 2. 在子组件,使用componentDidMount()方法,将子元素高度传递给父组件。这个方法会在子元素挂载完成后自动调用。 ```javascript class ChildComponent extends React.Component { componentDidMount() { const height = this.childRef.current.offsetHeight; this.props.onHeightChange(height); } render() { return ( <div ref={this.childRef}> // 子元素内容 </div> ); } } ``` 3. 在父组件,定义一个状态变量来保存子元素高度,然后将这个状态变量传递给子组件。 ```javascript class ParentComponent extends React.Component { constructor(props) { super(props); this.state = { height: 0 }; this.handleHeightChange = this.handleHeightChange.bind(this); } handleHeightChange(height) { this.setState({ height: height }); } render() { return ( <div style={{ height: this.state.height }}> <ChildComponent onHeightChange={this.handleHeightChange} /> </div> ); } } ``` 在这个例子,父元素高度会根据子元素高度来动态设置。当子元素高度发生变化时,子组件会将新的高度传递给父组件,父组件会重新渲染并设置自己的高度

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值