样式表未设置React组件的样式

时间:2019-11-15 15:21:35

标签: reactjs webpack sass styles

我搜索了很多类似的问题,但无法提出解决方案。

我将React.js与我的工作项目集成在一起。我正在使用Webpack。

除样式外,所有内容均可正常运行。

我有Style.scss,并将此文件导入到我的react文件中。编译时没有错误,但实际样式不适用于该元素。

内联样式的作品和其他通常包含的类也可以。

Style.scss

.wtf {
  font-weight: bold;
  font-size: 40px;
}

Test.js

import React from 'react';
import '../Styles/Style.scss';
const style = {
  border: 'solid 5px green'
};

export default class Test extends React.Component {
  render() {
    return (
      <div style={style} className='wtf text-danger'>
        Am I React.Component? And I am working too?
      </div>
    );
  };
}

根据上面的代码段,text-danger应用红色,而border:solid 5px green也适用,但是Style.scss中指定的样式无效。

我检查了编译文件,似乎我的scss样式代码存在于其中

enter image description here

这是浏览器中的结果

enter image description here

我的webpack.config.js文件内容如下:

const path = require( 'path' );

module.exports = {
  mode: 'development',
  entry: {
    rooms: './react-src/rooms/rooms.js',
    tasks: './react-src/tasks/tasks.js'
  },
  output: {
    filename: '[name].js',
    path: path.resolve('../htdocs/react-dist')
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          // style-loader
          { loader: 'style-loader' },
          // css-loader
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          },
          // sass-loader
          { loader: 'sass-loader' }
        ]
      },
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  }
};

有什么问题吗?

已解决

根据我的示例和Webpack配置,它正在编译样式,因此生成了新的类名。

enter image description here

因此,上面突出显示的巨大标记是我必须使用的实际类名。

它可以作为对象导入,因此我可以将类名作为属性来访问。

这是它的工作方式。

import React from 'react';
import style from '../Styles/Style.scss';

export default class Test extends React.Component {
  render() {
    return (
      <div className={style.wtf}>
        Am I React.Component? And I am working too?
      </div>
    );
  };
}

1 个答案:

答案 0 :(得分:1)

如果您将webpack配置修改为:

{...
  loader: 'css-loader',
    options: {
     modules: false
    },
...}

您可以使用常规的className属性