react设置style是需要一个object对象的
var divStyle = { color: 'white', backgroundImage: 'url(' + imgUrl + ')', WebkitTransition: 'all', // note the capital 'W' here msTransition: 'all' // 'ms' is the only lowercase vendor prefix }; ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);
但有的时候,我们需要显示原生的style,比如接口里面返回的
"topOne": { "title": "测试悬赏", "style": "font-weight: bold;color: #3C9D40;background-color: #3300CC;", "url": "http://xxx.com" }
然后正确的姿势依旧是需要把string转为object对象
handleStyle(style) { let newStyle = {}; if (style) { for (let v of style.split(';')) { let arr = v.split(':'); newStyle[arr[0].replace(/-(.)/, function(w,v) { return v.toUpperCase(); })] = arr[1]; } } return newStyle; } <span className="notice" style={this.handleStyle(msg.style)}>{msg.title}</span>