如何将JSON样式对象转换为CSS字符串?

nea*_*sic 4 javascript css inline-styles requestanimationframe reactjs

我想设置我的元素的样式:

this.refs.element.style = {
    ...this.props.style,
    background: 'blue',
};
Run Code Online (Sandbox Code Playgroud)

但显然你不能使用一个对象来设置ref的样式.我必须使用CSS样式字符串;分隔prop:values

我知道大多数人都会在渲染功能中设置样式,但出于性能原因,我无法重复渲染.

nea*_*sic 12

我只是Object.entries用分号爬行并减少

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

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

它upwraps background:'blue',到background:blue;这对CSS效果很好


用短划线小写字母替换任何大写字母

propName = propName.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);
Run Code Online (Sandbox Code Playgroud)

  • 2021 年谁需要 IE 支持? (2认同)

Art*_*rev 5

这个解决方案适用于 IE 并处理像 backgroundColor 这样的驼峰键

const style = {
    width: '1px',
    height: '1px',
    backgroundColor: 'red',
    transform: 'rotateZ(45deg)',
}
const styleToString = (style) => {
    return Object.keys(style).reduce((acc, key) => (
        acc + key.split(/(?=[A-Z])/).join('-').toLowerCase() + ':' + style[key] + ';'
    ), '');
};

console.log(styleToString(style));
// output - "width:1px;height:1px;background-color:red;transform:rotateZ(45deg);"
Run Code Online (Sandbox Code Playgroud)