gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:06:28 28 4
gpt4 key购买 nike

我需要使用 React JS 获取 html 元素的宽度。当我这样做时 console.log(this.widthPromoLine)componentDidMount() ,它有效,但是当我这样做时 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;
}

最佳答案

访问 clientWidth在将 ref 分配给变量 this.widthPromoLine 之后在 componentDidMount然后像下面这样设置。还有 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)}
/>
);
}
}

希望这可以帮助 !

关于html - 如何在 React JS 中获取 html 元素的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62365501/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com