简体   繁体   English

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

[英]Why is my CSS not applying to my React components?

Say I'm creating a React app and have some CSS for components.假设我正在创建一个 React 应用程序,并且有一些 CSS 用于组件。 I've added the style-loader and css-loader to my webpack config here:我已将 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"
};

I have a simple CSS file just to test on one component:我有一个简单的 CSS 文件,仅用于测试一个组件:

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

In my app I'm applying the classname to a element in my component and importing my CSS在我的应用程序中,我将类名应用于组件中的元素并导入我的 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)

I'm also importing the CSS file in the same way in the ContactList component itself.我还在 ContactList 组件本身中以相同的方式导入 CSS 文件。 The rest of the project is here .项目的rest在这里 I would have expected to see an outline around my comtactsList but there is not.我本来希望在我的 comtactsList 周围看到一个大纲,但没有。 There is no CSS when I inspect the page.我检查页面时没有 CSS。 Why is this not getting applied?为什么这没有得到应用?

In a react project created with create-react-app or npx create-react-app , I also had the same issue.在使用create-react-appnpx create-react-app 创建的反应项目中,我也遇到了同样的问题。

I had imported index.css file in my App Component but my styles were not being applied properly to my React Components.我在我的App 组件中导入了 index.css文件,但我的样式没有正确应用于我的 React 组件。

I even tried directly adding index.css file in my html file in the public folder and using link tag to link to my index.css file (which resides within src folder).我什至尝试直接在公用文件夹中的 html 文件中添加index.css文件,并使用链接标记链接到我的 index.css 文件(位于 src 文件夹中)。

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

That also didn't work.那也没有用。

Finally, I read an article about 7 ways to apply CSS into React.最后,我读了一篇关于将 CSS 应用到 React 的 7 种方法的文章。 One best way was to install node-sass into our project and use index.scss ( import './index.scss') into App Component instead of index.css .一种最好的方法是将node-sass安装到我们的项目中,并使用index.scss (import './index.scss')代替index.cssApp Component中。

And Hurray,.!万岁,.! My CSS worked fine, All the Media Queries started to work fine.我的 CSS 工作正常,所有媒体查询开始工作正常。

Below is the code snippet you can try.以下是您可以尝试的代码片段。

 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; } }

To install node-sass, simple do npm install node-sass --save Then rename all your .css files with .scss and your project with work properly.要安装 node-sass,只需执行npm install node-sass --save然后将所有.css文件重命名为.scss并且您的项目可以正常工作。

The package.json should have the node-sass dependency added as shown below: package.json应该添加了node-sass依赖项,如下所示:

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

Hope this will help many developers:)希望这会帮助许多开发人员:)

It would be helpful to see your React component as well.查看您的 React 组件也会很有帮助。

Given this code, you are passing className as a property into the component rather than assigning a class to it:鉴于此代码,您将 className 作为属性传递到组件中,而不是为其分配一个类:

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  render() {
    return (
      <div>
        /** This line specifically **/
        <ContactList className="contactList" />
        <ContactDetail />
        <AddContactModal />
      </div>
    );
  }
}

Inside your component, you would need to use className={this.props.className} on a regular HTML tag inside of your component in order to pass the className through.在您的组件内,您需要在组件内的常规 HTML 标记上使用className={this.props.className}才能传递 className。

You can add your specific css file to index.js directly.您可以将特定的 css 文件直接添加到 index.js。 (like this import './master.css' ) (像这样import './master.css'

According to the react documentation here the className can be applied to all DOM regular element such as <div> , <a> , ...根据此处的反应文档,className 可以应用于所有 DOM 常规元素,例如<div><a> ,...

Does your CSS works with the regular tag <div className='contactList'>hello</div> ?您的 CSS 是否适用于常规标签<div className='contactList'>hello</div>

It took me a while, but the add the followng to index.html under the public directory works for me.我花了一段时间,但将以下内容添加到public目录下的index.html对我有用。 This assumes that you are using create-react-app .这假设您正在使用create-react-app

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

Styling React Using CSS使用 CSS 对 React 进行样式化

I had a problem with applying css file to my react component, which solved by adding a.module.css extension to my css file name.我在将 css 文件应用于我的 React 组件时遇到问题,通过在我的 css 文件名中添加 a.module.css 扩展名解决了这个问题。 I found the answer here in w3schools在 w3schools找到了答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM