[英]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.