我在使用 React 时遇到问题,不知道为什么,但 React 没有附加属性 class
在渲染的 HTML 代码中。我在body中导入css文件,在react脚本中导入样式,编写className属性等等。
页面上的结果将在没有类的情况下被阻止 – <div>test</div>
在 App.js
import React, {Component} from 'react';
import styles from '../assets/main.css';
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div className={styles.test}>test</div>
</div>
);
}
}
在 main.css
.test {
color: red;
}
Webpack 配置
const HTMLWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
const webpack = require('webpack');
module.exports = {
entry: [
'react-hot-loader/patch',
__dirname + '/app/index.js'
],
devServer: {
hot: true
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
}
]
},
output: {
filename: 'transformed.js',
path: __dirname + '/build'
},
plugins: [
HTMLWebpackPluginConfig,
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
],
resolve: {
extensions: ['.js', '.jsx', '.css']
}
};
最佳答案
导入 CSS 样式表只会导致 Webpack 将其与 JavaScript 的其余部分捆绑在一起。您不能将 styles.test
添加为属性,这不会执行任何操作。您需要将 className
指定为字符串,就像 HTML 元素一样。
render() {
return (
<div>
<div className="test" >test</div>
</div>
);
}
关于javascript - React 不会从 className 中追加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47665069/