首页 > 解决方案 > How to create a global style in React

问题描述

I'm working on a project for school where one is able to create HTML elements by using Selection.js (visual selection turns into an HTML element). Currently, the user is able to write CSS in a CodeMirror editor. After the user applies the CSS by clicking a button, the styling is directly inserted onto the created React component trough props.

My main goal is to allow the user to create multiple elements with multiple styling rules, to then (in the end) export the created elements along with their styling.

I've imported JSS, because of the createStyleSheet function that generates styling based up on a JavaScript CSS object (which comes from the CodeMirror input) and because of the fact that the directly injected style trough props is not reusable (because it doesn't contain classes, just properties). The problem with JSS is that it generates styling in the form of .mySpecialClass-0-1 {...}

This is the code that I'm using when the user applies the style (on click).

 onStyleInput(e) {
        e.preventDefault();
        try {
            let style= cssToObject(this.codeMirror.getValue(), {camelCase: true});
            this.styleSheet = jss.createStyleSheet(style, {link: true}).attach();
            console.log(this.styleSheet);
        }
        catch (exception) {
            // console.log("Something went wrong, check your css syntax");
            console.log(exception);
        }
    }

The result I expected from JSS was styling in the form of .mySpecialClass {...}, without the unique id's.

I've been looking trough the JSS API, but there doesn't seem to be an available boolean to toggle the unique id generation.

Is there a better way of achieving my goal?

Thanks in advance!

标签: cssreactjsjss

解决方案


让 JSS 类没有 ID 的最简单方法是将其设为“全局”样式。这意味着,我们有全局 CSS 样式,它们没有单独附加到元素上。而不是在没有真正利用 JSS 结果的情况下放置/设置 HTML className。他们在文档页面的“插件”部分将其称为“全局选择器”。

您可以在此处找到文档:https ://cssinjs.org/jss-plugin-global?v=v10.0.0-alpha.7


推荐阅读