标准html内联样式:
<div style="background-color:blue, height:500px; width:500px;">Foo</div>
我想在反应中做到这一点:
this.state = {
specialDiv : 'backgroundColor:"blue", height: 500, width:500'
}
在html中:
<div style={{ this.state.specialDiv }}>Foo</div>
它不起作用,但可以使类似的东西,使用类不可能,使风格完全动态?
(我正在考虑如何让用户动态选择自己的动态样式,而课程则无法实现。)
提前致谢。
答案 0 :(得分:2)
style
属性接受一个对象;该对象应该具有CSS属性作为键,并将这些属性的值作为值。所以:
// note: you should only ever set `this.state` directly when using
// ES6 classes, and even then only in the constructor
this.state = {
specialDiv: {
backgroundColor: "blue",
height: 500,
width: 500
}
};
// ...
// `this.state.specialDiv` is already an object,
// no need to wrap it in extra curlies
<div style={this.state.specialDiv}>Foo</div>