問題描述
我試圖在 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 訪問樣式?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!