简体   繁体   English

将JSON CSS应用于React组件?

[英]Apply JSON CSS to React component?

I'm creating a component that must pass along JSON-ified CSS to an external source which uses it to render a styled iframe. 我正在创建一个组件,该组件必须通过JSON格式的CSS传递到外部源,该外部源使用它来呈现样式化的iframe。 Some of these styles should affect part of the parent, but all will need to be passed along. 这些样式中的某些样式应影响父项的一部分,但所有样式都需要传递。

Is there a good way to interpret the passed in JSON/CSS and apply it? 有没有很好的方法来解释并应用JSON / CSS?

Would it be better to accept CSS in another form in the parent, but then translate it to JSON before passing it along? 在父级中接受其他形式的CSS更好,然后在将其传递之前将其转换为JSON会更好吗?

The JSON would be passed as something like this: 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", } }; 

Install css-to-json 安装css-to-json

npm install css-to-json

Use it. 用它。

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

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

You don't have to accept CSS in another form. 您不必接受其他形式的CSS。

Try this when applying the styles: 应用样式时请尝试以下操作:

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]);
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM