Style
inline style
行内样式实现样式私有化
- 应用:条件动态样式
export default class Demo extends React.Component {
render() {
return <div style={{ fontSize: "20px" }}>hello world</div>
}
}
CSS Module
tip
- 1.样式都写在 xxx.module.css 文件中这样的文件是 CSS 文件,不能在使用 less/sass/stylus 这样的预编译语言
- 2 基于 ES6Module 模块规范导入进来 import style from /xxx.module.css
- style 存储的是一个对象
- 对象中包含多组键值对:
- 键:我们之前才 css 中编写的样式类名 box
- 值:经过 webpack 编译后的样式类名 Nav_boxc_6EW30 => [组件名_样式类名_hash 值]
- 3.编写的 CSS 样式会被编译,为混淆后的类名了[和上述对象中编译后的值一样] 4 在组件中,所有元素的样式类,基于 style.xxx 去操作!!!
Demo.module.css
.box {
width: 100px;
height: 200px;
background: red;
color: #fff;
}
.main {
font-size: 30px;
}
/* 不能使用sub-child,否则js中不方便使用 */
/* 强制不编译 */
:global(.subChild) {
font-weight: bold;
}
css module在组件中的使用
import React from "react"
// 使用ES6语法导入CSS文件
import styled from "./Demo.module.css"
export default function Demo() {
console.log(styled)
return (
<div className={styled.box}>
<div className={styled.main}>1</div>
<div className={styled.subChild}>2</div>
</div>
)
}
react-jss
import React from "react"
// 需要单独安装npm install react-jss
import { createUseStyles } from "react-jss"
/**
* 使用react-jss创建自定义css, 存储json对象
*/
const useStyles = createUseStyles({
box: {
backgroundColor: "blue",
width: "200px",
height: "200px",
},
main: (props) => {
// 在最外层可以使用传入的props进行css拼接
// 可以实现css in js的动态控制
return {
"& a": {
color: props.color,
},
}
},
})
/**
* 只有函数组件可以使用react-jss
* 如果是类组件,需要使用js闭包做代理(HOC=Higer-order-components,高阶组件)
*/
export default function Demo() {
// 执行useStyles函数
let { box, main } = useStyles({
// 并且传递参数
color: "red",
})
return (
<div className={box}>
<div className={main}>
<a>link href</a>
</div>
</div>
)
}
scoped-component
定义样式
import styled from "styled-components"
const MainColor = "red" // 定义全局变量
export const Nav = styled.nav`
background-color: lightblue;
width: 100%;
height: 100vh;
.box1 {
background: ${MainColor};
height: 50%;
// 这里可以拿到传递的属性
font-size: ${(props) => props.fontSize}px;
}
.box2 {
background: green;
height: 50%;
&:hover {
background: #b90b28;
}
}
`
export const Title = styled.h1.attrs((props) => {
return {
// 这里指定默认值参数
fontSize: props.fontSize || 30,
}
})`
font-weight: bold;
// 使用默认值参数
font-size: ${(props) => props.fontSize}px;
`
使用样式
import React from "react"
import { Nav, Title } from "./demo27.styled"
const Demo = () => {
return (
<div>
<Nav fontSize={80}>
<div className="box1">
<span>box1</span>
<Title fontSize="50">Here is a title.</Title>
</div>
<div className="box2">box2</div>
</Nav>
</div>
)
}
export default Demo