簡體   English   中英

如何在 React JS 中獲得 html 元素的寬度?

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

我需要使用 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; }

在將 ref 分配給componentDidMount中的變量this.widthPromoLine后訪問clientWidth ,然后將其設置如下。 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)}
      />
    );
  }
}

希望這可以幫助 !

您可以使用它的類名獲取內容的寬度,如下所示。

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

然后更新 state,

this.setState({moveContent: width})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM