【问题标题】:CSS file is not working in React Component file [closed]CSS文件在React Component文件中不起作用[关闭]
【发布时间】:2021-12-15 07:30:14
【问题描述】:

我在 js 文件中导入了 css 文件,但它没有改变我的代码的任何样式效果。我试图解决这个问题,但不能这样做。似乎一切都很好,但仍然无法正常工作。它不会对代码的任何部分产生样式效果。

.js 文件:

import React from 'react';
import classes from './Cockpit.css';

const cockpit = (props) => {
    let clases = [];
    let btnClass = '';
    
    if(props.showPersons) {
        btnClass = classes.Red;
    }

    if (props.persons.length <= 2) {
      clases.push(classes.red);
    }
    if (props.persons.length <= 1) {
      clases.push(classes.bold);
    }
    
    return (
        <div className={classes.Cockpitt}>
            <h1>Hi, I'm a React App</h1>
            <p className={clases.join(' ')}>This is really working!</p>
            <button 
                // style={style}
                className={btnClass}
                onClick={props.clicked}>Toggle Persons</button>
        </div>
    );
};

export default cockpit;

CSS 文件:

.red {
    color: red;
}
  
.bold {
    font-weight: bold;
}


.Cockpitt button {
    border: 1px solid blue;
    padding: 16px;
    background-color: green;
    font: inherit;
    color: white;
    cursor: pointer;
}

.Cockpitt button:hover {
    background-color: lightgreen;
    color: black;
}

.Cockpitt button.Red {
    background-color: red;
}

.Cockpitt button.Red:hover {
    background-color: salmon;
    color: black;
}

【问题讨论】:

    标签: css reactjs


    【解决方案1】:
    1. 不要在 CSS 上使用大写

    2. 只使用 import 关键字,不需要将其作为默认对象获取,也没有使用其中的键的选项,只是:

    import './Cockpit.css';
    

    至于动态类 - 使用 JS 代码定义名称,而不是外部 CSS 文件 喜欢:

    const classes = {...}
    return (
            <div className={isCockpitt ? classes.cockpitt : 'else-class'}>
                <h1>Hi, I'm a React App</h1>
            </div>
        );
    

    【讨论】:

      【解决方案2】:

      我已经通过将 css 文件名更改为:

      import classes from './Cockpit.module.css';
      

      问题就解决了!

      【讨论】:

        猜你喜欢
        • 2012-02-17
        • 2023-01-08
        • 2012-02-16
        • 2016-04-18
        • 2021-11-24
        • 1970-01-01
        • 2019-03-25
        • 1970-01-01
        • 2012-09-23
        相关资源
        最近更新 更多