代码之家  ›  专栏  ›  技术社区  ›  neaumusic

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

  •  13
  • neaumusic  · 技术社区  · 7 年前

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

    但是很明显,你不能用一个对象来设置ref的样式。我必须使用CSS样式的字符串 ; prop:values

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

    5 回复  |  直到 4 年前
        1
  •  34
  •   neaumusic    3 年前

    一个有效的答案是 map join Object.entries 带分号:

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

    它打开了 background:'blue', background:blue;


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

    k = k.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`);
    
        2
  •  6
  •   Artem Bochkarev    4 年前

    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);"
        3
  •  2
  •   Chetan Jain    4 年前

    使用 https://www.npmjs.com/package/json-to-css 。注意,它不会在最后一个属性中添加分号来修复它,您可以用它来美化它 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;
        }
       
    
        4
  •  1
  •   Tofandel    3 年前

    我添加了一个代码片段来完成相反的转换(字符串到对象),这可能对任何在这里遇到障碍的人都有用

    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)));
        5
  •  -1
  •   Kent Wood    5 年前

    css 中的函数 @material-ui/system 我可以帮你 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>
      );
    }