清除导入 CSS

Clear imported CSS

上下文

我正在使用 React 路由器。我的大部分 routes/pages 包括某种 .css 用于他们的组件 + 隐式 antd (UI 框架)样式表:

import '../styles.css';

这样我的应用程序中声明的所有视图都会自动继承这些样式表。

问题

我现在需要一个 route/page 从任何其他样式表开始的干净。

是否可以定义一旦呈现页面组件,就从呈现的视图中删除任何其他样式表?


我尝试了什么?

我尝试从 <App> 组件声明中删除导入(假设 create-react-app 基础)。但是每个页面组件都会清楚地导入这些样式,因此当我导入这些组件时,antd 样式也将被导入。

更不用说 antd 作为 npm 依赖项安装的事实可能包含这些样式。

常见问题解答

Why do you need this if all styles for each component are written independently from each other? Can't you just not render those components?

我不会渲染那些组件。这主要是 antd bodyfont-family 等默认样式的问题。

您可以使用内联样式独立设置组件样式。即使导入了各种样式表,你也可以这样做:

class SomeComponent extends React.Component {
  ...

  render() {
    return (
      <div style={{ font-family: 'sans-serif', color: 'red', padding: 10 }}>
        This will override imported styles.
      </div>
    );
  }
}

您可以使用 style-it

来完成

组件 A

class AppA extends React.Component {
  render() {
    return (
      <div>
        <Style>
          {`
            body {
              font-size: small;
              font-family: arial;
            }
            h1 {
              font-size: large;
              color: red
            }

         `}
        </Style>
        <h1> Component A this defualt style for h1 red</h1>
      </div>
    )
  }
}

组件 B

class AppB extends React.Component {

  render() {
    return (
      <div>
        <Style>
          {`
            body {
              font-size: small;
              font-family: arial;
              background: #f1f1f1;
            }
            h1 {
              font-size: large;
              color: blue
            }
         `}
        </Style>
        <h1> Component B this defualt style for h1 blue</h1>
      </div>
    )
  }
}

工作示例

不是这个特定问题的答案,但是如果你在寻找如何从 React 应用程序中取消导入 css 文件时发现这个 post(就像我一样),那么有一个此处的解决方案:

对于这个具体问题,我会使用 emotion's <Global/> Component