问题:突然发现一个页面的样式覆盖了另一个页面的样式,但是两个页面是独立开发的,样式也是分开写的,互相没有引用
原因:搜索发现是因为react会把所有的样式文件都放到<head>里面(如下图),这样如果类名重复,样式是会互相覆盖的。
解决方法:我搜索了一下,本质上都是让类名不一致。
一:使用css modules
1.1 改样式文件名 xxx.scss-->xxx.module.scss
1.2 改引用方法 import './demo.scss'-->import styles from './demo.scss'
1.3 改类名写法 className=“btns"-->className={styles.btns}
css modules会自动补充类名(例如btns_哈希值),保证类名的唯一性。
二:styled-components
1.1 安装
$ npm install styled-components
$ yarn add styled-components
1.2 使用
import styled from 'styled-components';
const Wrapper = styled.section`
margin: 0 auto;
width: 300px;
text-align: center;
`;
const Button = styled.button`
width: 100px;
color: white;
background: skyblue;
`;
render(
<Wrapper>
<Button>Hello World</Button>
</Wrapper>
);
这个方法没有用过哈哈,感觉很好用~