【问题标题】:unable to use styles from local css file无法使用本地 css 文件中的样式
【发布时间】:2018-02-15 15:35:13
【问题描述】:

我正在创建 reactjs Web 应用程序,我正在尝试使用本地 css 文件中的样式。源代码供参考。

/src/css/aboutcompany.css

.center {
    text-align: center;
    color: red;
}

/src/AboutCompany.js

import React,{Component} from 'react';
import style from './css/aboutcompany.css';

class AboutCompany extends Component{
  render(){
    return(
      <div>
        <p className="style.center"> Company</p>
        <hr/>
        Technologies  is leading  Company  providing end to end software solutions to customers globally. We are specialized in every vertical of industries and deliver quality solutions using latest technologies.
      </div>
    )
  }
}

export default AboutCompany;

webpack.config.js

var config = {
   entry: './src/index.js',
   output: {
      path:'/build/',
      filename: 'index.js',
   },
   devServer: {
      inline: true,
      port: 8081,
      historyApiFallback: true
   },
   module: {
      rules: [
        {
      test: /\.(jpg|png|svg)$/,
      use: 'url-loader'
    },
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: 'babel-loader'

         },
         {
          test: /\.css$/,
          use: 'css-loader'
        }
      ]
   }
}
module.exports = config;

正如您在 &lt;p className="style.center"&gt; Company&lt;/p&gt; 的 AboutCompany.js 中看到的那样,我们正在尝试使用 css 类 center ,但它不起作用。谁能告诉我哪里错了。

【问题讨论】:

  • 试过className={style.center}?
  • import './css/aboutcompany.css';className="center"?

标签: reactjs css-loader


【解决方案1】:

要在开发中使用css模块,首先你需要安装style-loader:

$ npm install style-loader --save-dev

然后在您的配置中将modules=true 作为选项传递给css-loader

{
  test: /\.css$/,
  use: ['style-loader', 'css-loader?modules=true']
}

最后在你的 jsx 代码中你可以这样调用你的类:

<p className={styles.center}/>

你就完成了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多