React顯示原生css style樣式在dom對象裏

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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章