如何获得反应元素的宽度 [英] How to get the width of a react element

查看:38
本文介绍了如何获得反应元素的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个范围输入,在滑块拇指正上方显示一个工具提示.

我在网上浏览了一些普通的 JS 示例,似乎我需要有元素的宽度才能完成.

所以我只是想知道如何获得元素宽度?

几乎等同于 JQuery 方法 $(element).width()

解决方案

 class MyComponent extends Component {构造函数(道具){超级(道具)this.myInput = React.createRef()}组件DidMount(){console.log(this.myInput.current.offsetWidth)}使成为 () {返回 (//新方法 - 从 React@16.3 开始<div ref={this.myInput}>一些元素</div>//传统方式//

this.myInput = ref}>some elem</div>)}}

Im trying to create a range input that displays a tooltip right above the slider thumb.

I went through some vanilla JS examples online and it seems that I need to have the width of the element to acomplish that.

So I was just wondering how to get the elements width?

Pretty much the equivalent of the JQuery method $(element).width()

解决方案

    class MyComponent extends Component {
      constructor(props){
        super(props)
        this.myInput = React.createRef()
      }

      componentDidMount () {
        console.log(this.myInput.current.offsetWidth)
      }

      render () {
        return (
        // new way - as of React@16.3
        <div ref={this.myInput}>some elem</div>
        // legacy way
        // <div ref={(ref) => this.myInput = ref}>some elem</div>
        )
      }
    }

这篇关于如何获得反应元素的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆