为什么我的 CSS 不适用于我的 React 组件?

新手上路,请多包涵

假设我正在创建一个 React 应用程序并为组件提供一些 CSS。我已将 style-loader 和 css-loader 添加到我的 webpack 配置中:

 module.exports = {
  mode: 'development',
  entry: './client/index.js',
  module: {
    rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-react']
          }
      }
    }, {
      test: /\.css$/,
      loader: 'style-loader'
    }, {
      test: /\.css$/,
      loader: 'css-loader',
      query: {
        modules: true,
        localIdentName: '[name]__[local]___[hash:base64:5]'
      }
    }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  output: {
    path: __dirname + '/dist',
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: './dist'
  },
  devtool:"#eval-source-map"
};

我有一个简单的 CSS 文件,仅用于在一个组件上进行测试:

 .list-group-item {
    border: 1px solid black;
    outline-style: solid;
    outline-color: red;
    outline-width: medium;
}

在我的应用程序中,我将类名应用于组件中的元素并导入我的 CSS

 import React, { Component } from 'react'
import { connect } from 'react-redux'
import selectContact from '../actions/action_select_contact'
import { bindActionCreators } from 'redux'
import '../styles.css';

class ContactList extends Component {
  renderList() {
    return this.props.contacts.map((contact) => {
      return (
        <li
          key={contact.phone}
          onClick={() => this.props.selectContact(contact)}
          className='list-group-item'>{contact.firstName} {contact.lastName}</li>
      );
    });
  }
  render() {
    return (
      <ul className = 'list-group col-sm-4'>
        {this.renderList()}
      </ul>
    );
  }
}

function mapStateToProps(state) {
  return {
    contacts: state.contacts
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ selectContact: selectContact }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(ContactList)

我还在 ContactList 组件本身中以相同的方式导入 CSS 文件。项目的其余部分在 这里。我本来希望在我的 comtactsList 周围看到一个大纲,但没有。当我检查页面时没有 CSS。为什么这没有得到应用?

原文由 intA 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 260
1 个回答

在使用 create-react-appnpx create-react-app 创建的反应项目中,我也遇到了同样的问题。

我在我的 App 组件 中导入了 index.css 文件,但我的样式没有正确应用于我的 React 组件。

我什至尝试直接在公用文件夹中的 html 文件中添加 index.css 文件,并使用链接标记链接到我的 index.css 文件(位于 src 文件夹中)。

 <link rel="stylesheet" href="./../src/index.css">

那也没有用。

最后,我读了一篇关于将 CSS 应用到 React 的 7 种方法的文章。一种最好的方法是将 node-sass 安装到我们的项目中,并使用 index.scss (import ‘./index.scss’)代替 index.cssApp Component 中。

万岁!我的 CSS 工作正常,所有媒体查询开始工作正常。

以下是您可以尝试的代码片段。

 import React from "react";
import ReactDom from "react-dom";
import './index.scss';

// --- Data to work with ---
const books = [
  {
    id: 1,
    name: 'The Rudest Book Ever',
    author: 'Shwetabh Gangwar',
    img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
  },
  {
    id: 2,
    name: 'The Rudest Book Ever',
    author: 'Shwetabh Gangwar',
    img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
  },
  {
    id: 3,
    name: 'The Rudest Book Ever',
    author: 'Shwetabh Gangwar',
    img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
  },
  {
    id: 4,
    name: 'The Rudest Book Ever',
    author: 'Shwetabh Gangwar',
    img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
  },
];

const Book = ({ book }) => {
  return (
    <div className={"book"}>

      <img src={book.img} alt="book image" />

      <h3>{book.name}</h3>
      <p>{book.author}</p>
    </div>
  )
};

const Books = () => {
  return (
    <main className={"books"}>
      {
        books.map(book => {
          return (<Book book={book} key={book.id} />)
        })
      }
    </main>
  )
};

// Work a bit fast | one step at a time
const App = () => {
  return (
    <main>
      <h2>Books</h2>
      <Books />
    </main>
  )
}

ReactDom.render(<App />, document.getElementById("root"));
 /* --- Mobile First Design --- */
.books{
  text-align: center;
};

.book{
  border: 1px solid #ccc;
  text-align: center;
  width: 200px;
  padding: 1rem;
  background: #001a6e;
  color: #fff;
  margin:auto;
};

h2{
  text-align: center;
}

/* --- Adding Media Queries --- */
@media only screen and (min-width: 900px){
  .books,.persons{
    display:grid;
    grid-template-columns: 1fr 1fr;
  }
}

要安装 node-sass,只需执行 npm install node-sass --save 然后将所有 .css 文件重命名为 .scss 并且您的项目可以正常工作。

package.json 应该添加了 node-sass 依赖项,如下所示:

  "dependencies": {
    "node-sass": "^4.14.1",
    "react": "^16.8.3",
    "react-dom": "^16.8.3",
    "react-scripts": "2.1.5"
  },

希望这会帮助许多开发人员:)

原文由 Imran Rafiq Rather 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题