React如何获取DOM元素的样式?

想要通过ref或者findDOMNode方式获取样式,但是取出来的都是空值

import React from 'react'
import ReactDOM from 'react-dom'
import style from './index.css'
import SplitPanel from '../SplitPanel/index.jsx'

class Main extends React.Component {
  componentDidMount () {
    const dom = ReactDOM.findDOMNode(this)
    console.log('this style:', dom.style)
    console.log('input style:', this.textInput.style)
  }

  render () {
    return (
      <div className={style.wrapper} >
        <input type="text"
          ref={(input) => { this.textInput = input }} />
      </div>
    )
  }
}

export default Main

CodePen中测试

结果:
error one
error two

阅读 16k
3 个回答

知道了,dom.style得到的是行内样式,要用dom.currentStyle或者getComputedStyle(dom, null)取值。

生命周期不对,应该在componentDidUpdate 里面获取

新手上路,请多包涵

this.textInput.style只能获取dom行内的样式,行内如果没写样式的话,就是空的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题