如何从 React 访问样式?

新手上路,请多包涵

我试图在 React 中访问 div 的宽度和高度样式,但我遇到了一个问题。这是我到目前为止得到的:

 componentDidMount()  {
  console.log(this.refs.container.style);
}

render()  {
   return (
      <div ref={"container"} className={"container"}></div>  //set reff
   );
}

这有效,但我得到的输出是一个 CSSStyleDeclaration 对象,在 all 属性中我可以为该对象设置所有 CSS 选择器,但它们都没有设置。它们都设置为空字符串。

这是 CSSStyleDecleration 的输出:http: //pastebin.com/wXRPxz5p

非常感谢任何有关查看实际样式(事件继承的样式)的帮助!

谢谢!

原文由 mre12345 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 493
2 个回答

对于 React v <= 15

 console.log( ReactDOM.findDOMNode(this.refs.container).style); //React v > 0.14

console.log( React.findDOMNode(this.refs.container).style);//React v <= 0.13.3

编辑:

获取特定样式值

console.log(window.getComputedStyle(ReactDOM.findDOMNode(this.refs.container)).getPropertyValue("border-radius"));// border-radius can be replaced with any other style attributes;

对于 React v >= 16

使用回调样式或使用 createRef() 分配 ref。

 assignRef = element => {
  this.container = element;
}
getStyle = () => {

  const styles = this.container.style;
  console.log(styles);
  // for getting computed styles
  const computed = window.getComputedStyle(this.container).getPropertyValue("border-radius"));// border-radius can be replaced with any other style attributes;
  console.log(computed);
}

原文由 Vikramaditya 发布,翻译遵循 CC BY-SA 4.0 许可协议

下面是一个通过 React Refs.getComputedStyle 方法计算 CSS 属性值的例子:

 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 <div ref={this.divRef}>Some Text</div>
    }
}

原文由 Purkhalo Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议

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