【发布时间】:2020-06-13 21:00:27
【问题描述】:
我需要使用 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;
}
【问题讨论】:
-
这能回答你的问题吗? How to get the width of a react element?