【问题标题】:How can I get a width of html element in React JS?如何在 React JS 中获取 html 元素的宽度?
【发布时间】:2020-06-13 21:00:27
【问题描述】:

我需要使用 React JS 获取 html 元素的宽度。当我在componentDidMount() 中执行console.log(this.widthPromoLine) 时,它可以工作,但是当我执行this.setState({moveContent: this.widthPromoLine}) 时,它不会。

import React from 'react'
import './index.css'

class Promo extends React.Component {


    constructor(props){
        super(props)
        this.state = {
            moveContent: 0
        }
    }
    
    componentDidMount(){
        this.setState({moveContent: this.widthPromoLine})
    }
    
    render(){
      return <div 
                className="promo-content" 
                ref={promoLine => this.widthPromoLine = promoLine.clientWidth}> 
             </div>
    }


}
.promo-content {
  width: 1870px;
}

【问题讨论】:

标签: html css reactjs


【解决方案1】:

在将引用分配给componentDidMount 中的变量this.widthPromoLine 后访问clientWidth,然后将其设置如下。 setState 也是异步的,所以你需要在 setState 的回调中更新状态后做任何事情。

import React from "react";
import "./styles.css";

class Promo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      moveContent: 0
    };
  }

  componentDidMount() {
    this.setState({ moveContent: this.widthPromoLine.clientWidth }, () => {
      console.log(this.state);
    });
  }

  render() {
    return (
      <div
        className="promo-content"
        ref={promoLine => (this.widthPromoLine = promoLine)}
      />
    );
  }
}

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    您可以使用它的类名获取内容的宽度,如下所示。

    let width = document.querySelector(".promo-content").offsetWidth;
    

    然后更新状态,

    this.setState({moveContent: width})
    

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 1970-01-01
      • 2022-07-15
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      相关资源
      最近更新 更多