How to Access styles from React?

前端 未结 5 1644
时光取名叫无心
时光取名叫无心 2020-12-24 14:10

I am trying to access the width and height styles of a div in React but I have been running into one problem. This is what I got so far:

componentDidMount()         


        
5条回答
  •  误落风尘
    2020-12-24 14:53

    Here is an example of computing the CSS property value via React Refs and .getComputedStyle method:

    class App extends React.Component {
        constructor(props) {
            super(props)
            this.divRef = React.createRef()
        }
    
        componentDidMount() {
            const styles = getComputedStyle(this.divRef.current)
    
            console.log(styles.color) // rgb(0, 0, 0)
            console.log(styles.width) // 976px
        }
    
        render() {
            return 
    Some Text
    } }

提交回复
热议问题