1、模块化作用
- 防止全局污染,样式被覆盖
- 命名混乱
- css 代码冗余,体积庞大
2、CSS Modules
css-loader配置
{test: /\.css$/,/* 对于 css 文件的处理 */use:['css-loader?modules' /* 配置css-loader ,加一个 modules */]}
css定义
.text{color: red;}
js文件
import style from './style.css'export default () =>(<div><div className={ style.text } >验证 css modules </div></div>)
3、自定义命名和全局变量
自定义规则命名
{test: /\.css$/,/* 对于 css 文件的处理 */use:[{loader: 'css-loader',options:{modules: {localIdentName: "[path][name]__[local]--[hash:base64:5]", /* 命名规则 [path][name]__[local] 开发环境 - 便于调试 */},}},],}
全局变量
.text{color: blue;}:global(.text_bg) {background-color: pink;}
import style from './style.css'export default ()=><div><div className={ style.text + ' text_bg'} >验证 CSS Modules </div></div>
4、动态添加class
css定义:
.base{ /* ...基础样式 */ }.dark{ // 主题样式-暗色调background:#000;color: #fff;}.light{// 主题样式-亮色调border: 1px solid #000;color: #000;background: #fff;}
组件中引入 classNames 库:
import classNames from 'classnames'import Style from './index.less' /* less css module *//* 动态加载 */export default function Index(){const [ theme , setTheme ] = React.useState('light')return <div ><buttonclassName={ classNames(Style.base, theme === 'light' ? Style.light : Style.dark ) }onClick={ ()=> setTheme(theme === 'light' ? 'dark' : 'light') }>切换主题</button></div>}
5、CSS IN JS
在 index.js 写 React 组件:
import React from 'react'import Style from './style'export default function Index(){return <div style={ Style.boxStyle } ><span style={ Style.textStyle } >hi , i am CSS IN JS!</span></div>}
在同级目录下,新建 style.js 用来写样式:
/* 容器的背景颜色 */const boxStyle = {backgroundColor:'blue',}/* 字体颜色 */const textStyle = {color:'orange'}export default {boxStyle,textStyle}
style-components库使用
import styled from 'styled-components'/* 给button标签添加样式,形成 Button React 组件 */const Button = styled.button`background: #6a8bad;color: #fff;min-width: 96px;height :36px;border :none;border-radius: 18px;font-size: 14px;font-weight: 500;cursor: pointer;margin-left: 20px !important;`export default function Index(){return <div><Button>按钮</Button></div>}
style-components 可以通过给生成的组件添加 props 属性 ,来动态添加样式。
const Button = styled.button`background: ${ props => props.theme ? props.theme : '#6a8bad' };color: #fff;min-width: 96px;height :36px;border :none;border-radius: 18px;font-size: 14px;font-weight: 500;cursor: pointer;margin-left: 20px !important;`export default function Index(){return <div><Button theme={'#fc4838'} >props主题按钮</Button></div>}
