开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情
接着上一篇的内容,今天我们学习如何在React中使用css。
众所周知,在Vue中使用css,只要给style添加scoped属性就可以实现css的“作用域”功能,但是在React是不能这么操作的,那么css全局变量污染,命名方式混乱等问题在React中如何解决?让我们一起来看看React是如何实现css的模块化的。
React使用css模块化主要有两种方式
- Css modules 依赖于前端工程化工具将css交给js来动态加载
- Css in js 用js对象方式写css
CSS Modules
该方式可以将css当作js模块,可以像加载js模块一样加载css,通过自定义的命名方式生成唯一性的css类名,从根本上解决了全局变量污染,样式覆盖等问题。在webpack中使用css-loader,就可以实现css modules功能。在CRA(create react app)项目中,默认配置了该功能,按照下面的方式使用即可 ⚠️ less和sass的使用方式和css一样
// index.module.css 在cra中利用 xxx.module.css 命名css文件 实现css module
.hot {
color: red;
}
// index2.module.css
.text {
color: green;
}
import style from './index.css'
import style2 from './index2.css'
export default ()=>
<div>
<div className={ style.hot } >
css 模块化 style
</div>
<div className={ style2.text } >
css 模块化 style2
</div>
</div>
全局变量
:global(.hot) {
color: red;
}
import style from './index.css'
export default ()=>
<div>
<div className='hot' > // css 全局样式
css 模块化
</div>
</div>
样式继承
/* 按钮基础样式 */
.btn {
background: gray;
border-radius: 5%;
}
/* 警告按钮样式 */
.btn-alert {
composes: btn; // 继承自btn
background-color: red;
}
import style from './index.css'
export default ()=>
<div>
<button className={styles['btn-alert']}>警告按钮</button>
<button className={styles['btn']}>默认按钮</button>
</div>
CSS IN JS
用js对象写style,把js“样式对象”渲染成行内式,这样就从根本上解决了css全局污染,样式混乱等问题。并且以js的形式写css,可以像js那样去操作css,同时无需webpack等额外配置
import Style from "./style";
export default function Index() {
return (
<div>
<button style={Style.btnStyle}>按钮1</button>
<span style={Style.textStyle}>文字</span>
</div>
);
}
const btnStyle = {
backgroundColor: "gray"
};
const textStyle = {
color: "red"
};
export default {
btnStyle,
textStyle
};
style-components库使用
import styled from 'styled-components'
/* 给Button组件设置样式 */
const Button = styled.a`
background: gray;
color: #fff;
padding: 5px 10px;
border: none;
border-radius: 20px;
cursor: pointer;
`;
export default function Index() {
return (
<div>
<Button>按钮</Button>
</div>
);
}
如果用原生css in js 动态修改css 会比较麻烦,而使用style-components库就会直观方便些。
使用props动态设置样式
import styled from "styled-components";
/* 给Button组件设置样式 */
const Button = styled.a`
background: ${ props => props.type === 'warning' ? 'red' : 'gray' };
color: #fff;
padding: 5px 10px;
border: none;
border-radius: 20px;
cursor: pointer;
`;
export default function Index() {
return (
<div>
<Button type={'warning'}>按钮</Button>
</div>
);
}
style-components的继承方式
import styled from "styled-components";
/* 给Button组件设置样式 */
const Button = styled.a`
background: gray;
color: #fff;
padding: 5px 10px;
border: none;
border-radius: 20px;
cursor: pointer;
`;
/* 继承Button组件的样式 */
const AlterButton = styled(Button)`
background: red;
`
export default function Index() {
return (
<div>
<Button>按钮</Button>
<AlterButton>警告按钮</AlterButton>
</div>
);
}
关于React中css如何使用就学习到这里,下一章我们开始学习强大的React Hooks。
See you next time!👋