简体   繁体   English

如何仅在渲染时在 React 组件中导入 SCSS 文件?

[英]How to import SCSS files in React component only when it renders?

I have a large React.js project, for which I have created separate SCSS files for separate React Components.我有一个大型 React.js 项目,为此我为单独的 React 组件创建了单独的 SCSS 文件。 The problem is styles in one component, let's say Component_1, are available in other components.问题是 styles 在一个组件中,比如说 Component_1,在其他组件中可用。

I have tried using import() the SCSS files within the Componets' componentWillMount() methods.我尝试在组件的componentWillMount()方法中使用import()的 SCSS 文件。

// instead of this
import "../Styles/_header.scss";

class Header extends React.Component {
  // I am trying this
  componentWillMount() {
    import ("../Styles/_header.scss");
  }
}

But I have many functional components, and for that I am seaching an Webpack way or any other way, so that my SCSS files will be only available in the Components from which I am importing... Thanks但是我有很多功能组件,为此我正在搜索 Webpack 方式或任何其他方式,因此我的 SCSS 文件将仅在我从中导入的组件中可用...谢谢

I know it will have impact and you will need to refactor, but styled-components is your friend here.我知道它会产生影响,你需要重构,但styled-components是你的朋友。

Basically, you add styling on component level.基本上,您在组件级别添加样式。 In combination with lazy loading components you only load your component with its styling when the components need to be rendered by React.结合延迟加载组件,您仅在组件需要由 React 渲染时才加载组件及其样式。

You can use this babel plugin to conditionally import things.你可以使用这个babel 插件有条件地导入东西。 Also in your functional components you can use the effect hook to replace componentWillMount/componentDidMount.同样在您的功能组件中,您可以使用效果挂钩来替换 componentWillMount/componentDidMount。

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

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