我试图在 React 中访问 div 的宽度和高度样式,但我遇到了一个问题.这是我到目前为止得到的:
componentDidMount() {console.log(this.refs.container.style);}使成为() {返回 (<div ref={"container"} className={"container"}></div>//设置参考);}
这可行,但我得到的输出是一个 CSSStyleDeclaration 对象,在 all 属性中,我可以为该对象设置所有 CSS 选择器,但它们都没有设置.它们都设置为空字符串.
这是 CSSStyleDecleration 的输出:http://pastebin.com/wXRPxz5p
任何有关查看实际样式(事件继承的样式)的帮助将不胜感激!
谢谢!
For React v <= 15
console.log(ReactDOM.findDOMNode(this.refs.container).style);//反应 v >0.14console.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 可以替换为任何其他样式属性;
<块引用>
对于反应 v>= 16
使用回调样式或使用 createRef() 分配 ref.
assignRef = element =>{this.container = 元素;}getStyle = () =>{常量样式 = this.container.style;控制台.log(样式);//用于获取计算样式const computed = window.getComputedStyle(this.container).getPropertyValue("border-radius"));//border-radius 可以替换为任何其他样式属性;控制台.log(计算);}
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!
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);
}
这篇关于如何从 React 访问样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!