简体   繁体   English

如何在 React JS 中获得 html 元素的宽度?

[英]How can I get a width of html element in React JS?

I need to get a width of html element, using React JS.我需要使用 React JS 获得 html 元素的宽度。 When I do console.log(this.widthPromoLine) in componentDidMount() , it works, but when I do this.setState({moveContent: this.widthPromoLine}) , it doesn't.当我在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; }

Access the clientWidth after the ref has been assigned to the variable this.widthPromoLine in componentDidMount and then set it like below.在将 ref 分配给componentDidMount中的变量this.widthPromoLine后访问clientWidth ,然后将其设置如下。 Also setState is async, so you need to do anything after the state has been updated in the callback of setState . setState也是异步的,因此您需要在setState的回调中更新 state 之后执行任何操作。

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)}
      />
    );
  }
}

Hope this helps !希望这可以帮助 !

You can get the width of content using it classname as follow.您可以使用它的类名获取内容的宽度,如下所示。

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

And after that update the state,然后更新 state,

this.setState({moveContent: width})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM