mre*_*345 17 javascript css attributes reactjs
我试图访问React中div的宽度和高度样式,但我遇到了一个问题.这是我到目前为止所得到的:
componentDidMount() {
console.log(this.refs.container.style);
}
render() {
return (
<div ref={"container"} className={"container"}></div> //set reff
);
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,但我得到的输出是一个CSSStyleDeclaration对象,在all属性中我可以为该对象的所有CSS选择器,但它们都没有设置.它们都设置为空字符串.
这是CSSStyleDecleration的输出:http://pastebin.com/wXRPxz5p
任何有关看到实际样式(事件继承的样式)的帮助将不胜感激!
谢谢!
Vik*_*tya 25
对于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
Run Code Online (Sandbox Code Playgroud)
编辑:
获取特定的样式值
console.log(window.getComputedStyle(ReactDOM.findDOMNode(this.refs.container)).getPropertyValue("border-radius"));// border-radius can be replaced with any other style attributes;
Run Code Online (Sandbox Code Playgroud)
对于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);
}
Run Code Online (Sandbox Code Playgroud)
这是通过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>
}
}
Run Code Online (Sandbox Code Playgroud)