小编典典

如何从React访问样式?

reactjs

我试图在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

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

谢谢!


阅读 253

收藏
2020-07-22

共1个答案

小编典典

对于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()分配引用。

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);
}
2020-07-22