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

时间:2019-10-01 17:41:28

标签: reactjs sass css-modules react-css-modules

我有一个很大的React.js项目,为此我为单独的React组件创建了单独的SCSS文件。问题是一个组件(例如Component_1)中的样式在其他组件中可用。

我尝试在组件的import()方法中使用componentWillMount()的SCSS文件。

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

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

但是我有很多功能组件,为此,我正在使用Webpack或其他任何方式,以便我的SCSS文件仅在我要从中导入的组件中可用...谢谢

2 个答案:

答案 0 :(得分:0)

我知道它会产生影响,您需要进行重构,但是styled-components是您的朋友。

基本上,您可以在组件级别添加样式。与惰性加载组件结合使用时,只有在需要由React渲染组件时,才使用其样式加载组件。

答案 1 :(得分:0)

您可以使用此babel plugin有条件地导入内容。同样,在功能组件中,您可以使用effect hook替换componentWillMount / componentDidMount。