将JSON CSS应用于React组件?

时间:2019-02-20 00:38:08

标签: javascript css reactjs

我正在创建一个组件,该组件必须通过JSON格式的CSS传递到外部源,该外部源使用它来呈现样式化的iframe。这些样式中的某些样式会影响部分父样式,但所有样式都需要传递。

是否有一种很好的方法来解释传入的JSON / CSS并将其应用?

在父级中接受另一种形式的CSS更好,但是在将其传递之前将其转换为JSON吗?

JSON将像这样传递:

const styles = { // optional
    "input": {
      "width": "100%",
      "font-family": "'Helvetica Neue',Helvetica,Arial,sans-serif",
      "font-size": "14px",
      "color": "#555",
      "height": "34px",
      "padding": "6px 12px",
      "margin": "5px 0px",
      "line-height": "1.42857",
      "border": "1px solid #ccc",
      "border-radius": "4px",
      "box-shadow": "0px 1px 1px rgba(0,0,0,0.075) inset",
      "-webkit-transition": "border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s",
      "transition": "border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s",
    },
    "select": {
      "width": "100%",
      "font-family": "'Helvetica Neue',Helvetica,Arial,sans-serif",
      "font-size": "14px",
      "color": "#555",
      "height": "34px",
      "padding": "6px 12px",
      "margin": "5px 0px",
      "line-height": "1.42857",
      "border": "1px solid #ccc",
      "border-radius": "4px",
      "box-shadow": "0px 1px 1px rgba(0,0,0,0.075) inset",
      "-webkit-transition": "border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s",
      "transition": "border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s",
    }
    };

1 个答案:

答案 0 :(得分:0)

安装css-to-json

npm install css-to-json

使用它。

// To JSON
var json = CSSJSON.toJSON(cssString);

// To CSS
var css = CSSJSON.toCSS(jsonObject);
  

您不必接受其他形式的CSS。

应用样式时,请尝试以下操作:

function camelize(str) {
        var bla = str.split('-')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join('');
    return bla && bla[0].toLowerCase() + bla.slice(1);
}

Object.keys(styles).map((key, index) => {
    Object.keys(styles[key]).map((key2, index2) => {
    key2 = camelize(key2)
    document.querySelector(key).style.key2 = styles[key][key2]);
  })
})