【发布时间】:2019-06-23 13:40:54
【问题描述】:
我正在使用 create-react-app 最新版本 2.1.3。我创建了一个演示应用程序来测试 css 模块,它在 create-react-app 2.1.3 中应该是开箱即用的,无需运行“npm 弹出”或执行配置文件修改。 但是由于某种原因,在 App css-module 文件中声明的样式会覆盖在子组件 css-module 文件中声明的样式。
我将生成的 App.js 用作嵌入另一个名为 Person.js 的子组件(实现人员卡片)的组件。这两个组件都使用 css-modules 并有自己对应的 App.module.css 和 Person.module.css css 文件。这两个组件都具有来自其 css 模块的独特样式的按钮元素。但是当我运行应用程序时,我可以在 chrome 开发人员工具中看到 Person 的按钮样式被删除,并且被 App.module.css 文件中声明的按钮类禁用,我不明白为什么。 css-module 的全部目的是仅向导入它们的组件声明 css 样式。
App.js
import React, { Component } from "react";
import Person from "./Person/Person";
import styles from "./App.module.css";
class App extends Component {
state = {
persons: [
{ id: "abcd", name: "John Do", age: 41 }
],
someOtherState: "Some other state",
showPersons: false
};
togglePersonsHandler = () => {
this.setState({
showPersons: !this.state.showPersons
});
};
render() {
let persons = null;
let btnClass = "";
if (this.state.showPersons && this.state.persons.length > 0) {
persons = (
<div>
{this.state.persons.map((person, index) => {
return (
<Person
key={person.id}
name={person.name}
age={person.age}
/>
);
})}
</div>
);
btnClass = styles.red;
}
const classes = [];
if (this.state.persons.length <= 2) {
classes.push(styles.red);
}
if (this.state.persons.length <= 1) {
classes.push(styles.bold);
}
return (
<div className={styles.App}>
<h1> Hi, I'm a react app </h1>
<p className={classes.join(" ")}>This is a paragraph!!!</p>
<button
className={btnClass}
onClick={this.togglePersonsHandler}
>
Toggle Persons
</button>
{persons}
</div>
);
}
}
export default App;
App.module.css
.App {
text-align: center;
}
.red {
color: red;
}
.bold {
font-weight: bold;
}
.App button {
background-color: green;
color: white;
font: inherit;
border: 1px solid blue;
padding: 8px;
cursor: pointer;
}
Person.js
import React from "react";
import styles from "./Person.module.css";
const person = props => {
return (
<div className={styles.Person}>
<p onClick={props.click}>
I'm {props.name} and i'm {props.age} years old.
</p>
<p>{props.children}</p>
<input type="text" onChange={props.changed} value={props.name} />
<button className={styles.personBtn}>Click Me</button>
</div>
);
};
Person.module.css
.Person {
width: 60%;
margin: 16px auto;
border: 1px solid #eee;
box-shadow: 0 2px 3px #ccc;
padding: 16px;
text-align: center;
}
.personBtn {
background-color: blue;
}
我希望 Person 组件内的按钮应该具有 Person.module.css 中定义的蓝色背景色,但实际结果是他们获得了 App.module.css .App 按钮样式(即绿色背景)
【问题讨论】:
标签: reactjs css-modules react-css-modules