Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

javascript - How to Access styles from React?

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()  {
  console.log(this.refs.container.style);     
}


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

This works but the output that I get is a CSSStyleDeclaration object and in the all property I can all the CSS selectors for that object but they none of them are set. They are all set to an empty string.

This is the output of the CSSStyleDecleration is: http://pastebin.com/wXRPxz5p

Any help on getting to see the actual styles (event inherrited ones) would be greatly appreciated!

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For 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

EDIT:

For getting the specific style value

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

For React v>= 16

assign ref using callback style or by using 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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...