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

How to convert a JSON style object to a CSS string?

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

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

但显然您不能使用对象来设置裁判的样式。我必须使用带有 ; 分隔 prop:values

的 CSS 样式字符串

我知道大多数人会在渲染函数中设置样式,但出于性能原因,我不能重复重新渲染。

一个有效的答案是 mapjoin Object.entries 分号:

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

const styleString = (
  Object.entries(style).map(([k, v]) => `${k}:${v}`).join(';')
);

它将 background:'blue', 解包为 background:blue;,这对 CSS

很有效

用破折号小写字母替换任何大写字母

k = k.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);

@material-ui/system中的css函数可以帮到你 在此处检查 more info

import React from 'react';
import styled, { ThemeProvider } from 'styled-components';
import NoSsr from '@material-ui/core/NoSsr';
import { createMuiTheme } from '@material-ui/core/styles';
import { compose, spacing, palette, css } from '@material-ui/system';

const Box = styled.div`
  ${css(
    compose(
      spacing,
      palette,
    ),
  )}
`;

const theme = createMuiTheme();

export default function CssProp() {
  return (
    <NoSsr>
      <ThemeProvider theme={theme}>
        <Box color="white" css={{ bgcolor: 'palevioletred', p: 1, textTransform: 'uppercase' }}>
          CssProp
        </Box>
      </ThemeProvider>
    </NoSsr>
  );
}

此解决方案适用于 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);"

使用https://www.npmjs.com/package/json-to-css. Note it will not add a semicolon to the last property to fix it you can beautify it with https://www.npmjs.com/package/cssbeautify 例子


    const cssbeautify = require('cssbeautify')

    const Css = require('json-to-css')

    const json = {
        "h1": {
            "font-size": "18vw",
            "color": "#f00"
        },
        ".btn": {
            "font-size": "18vw",
            "color": "#f00"
        }
    }


    const r = Css.of(json)
    console.log(r)

    const beautified = cssbeautify(r, {
        autosemicolon: true
    })

    console.log(beautified)

结果


  console.log src/utils/playground/index.spec.ts:22 // json-to-css
    h1{font-size:18vw;color:#f00}
    .btn{font-size:18vw;color:#f00}

  console.log src/utils/playground/index.spec.ts:29 // cssbeautify
    h1 {
        font-size: 18vw;
        color: #f00;
    }
    
    .btn {
        font-size: 18vw;
        color: #f00;
    }
   

加入@Artem Bochkarev 的精彩回答

我正在添加一个代码片段来进行相反的转换(字符串到对象),这可能对遇到这里问题的任何人派上用场

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] + ';'
  ), '');
};
const stringToStyle = (style) => {
  const styles = {};
  style.split(';').forEach((s) => {
    const parts = s.split(':', 2);
    if (parts.length > 1) {
      styles[parts[0].trim().replace(/-([a-z])/ig, (_, l) => l.toUpperCase())] = parts[1].trim();
    }
  });
  return styles;
};

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

console.log(stringToStyle(styleToString(style)));