我搜索了很多类似的问题,但找不到解决方案。
我将 React.js 集成到了我的工作项目中。我正在使用 Webpack。
除了样式之外,一切都运行正常。
我有Style.scss
我将此文件导入到我的 react 文件中。编译时没有错误,但实际样式并未应用于该元素。
内联样式工作和通常包含的其他类也可以。
样式.scss
.wtf {
font-weight: bold;
font-size: 40px;
}
测试.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 样式代码存在于其中
这是浏览器中的结果
我的 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 配置,它正在编译样式,从而生成新的类名。
所以,上面突出显示的那个巨大标记是我必须使用的实际类名。
它可以作为对象导入,这样我就可以将类名作为属性访问。
这就是它的工作原理。
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>
);
};
}
最佳答案
如果您将 webpack 配置修改为:
{...
loader: 'css-loader',
options: {
modules: false
},
...}
您可以使用常规的 className 属性
关于reactjs - 样式表没有设置 React 组件的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58879991/