2017-07-20 62 views
0

我想我的設置元素的風格,例如:如何將JSON樣式對象轉換爲CSS字符串?

this.refs.element.style = { 
    ...this.props.style, 
    background: 'blue', 
}; 

但很顯然,你不能使用對象設置裁判的風采。我必須使用一個CSS樣式字符串;分離prop:values

我知道,大多數人會設定在渲染功能的風格,但對於性能方面的原因,我不能重複再渲染。

回答

3

我剛爬Object.entries,並用分號

const style = { 
    ...this.props.style, 
    background: 'blue', 
}; 

const styleString = (
    Object.entries(style).reduce((styleString, [propName, propValue]) => { 
    return `${styleString}${propName}:${propValue};`; 
    }, '') 
); 

它upwraps減少background:'blue',background:blue;這對於CSS

效果很好
相關問題