简体   繁体   中英

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

I need to get a width of html element, using React JS. When I do console.log(this.widthPromoLine) in componentDidMount() , it works, but when I do this.setState({moveContent: this.widthPromoLine}) , it doesn't.

 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. Also setState is async, so you need to do anything after the state has been updated in the callback of 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)}
      />
    );
  }
}

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,

this.setState({moveContent: width})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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