行业知识
React引入css的几种方式以及应用
2026-11-02 09:57:57
来源:互联网转载
1.直接引入css文件
import "./parent.css"
2.引入css模块,定义文件名[组件名.module.css];该方式可避免类名的重复,每个组件都有独立的作用域,避免了全局污染,保证了类名的唯一性
import styles from "./parent1.module.css".title{ color: red;}{ background:'pink' }}我是父组件 3.第三方依赖库styled-components,需要下载第三方依赖库,定义每个组件的样式
��下载依赖库指令:npm install styled-components -S
()import styleComponents from "styled-components"// 自定义样式的组件 注意定义的首字母大写,不然不生效const StyleP = styleComponents.p` color: green; font-size: 30px; font-weight: bolder;`const StyleTitle = styleComponents.h1` color: red`第三方库引入css demo第三方库引入css demo
4.应用
(1)传参;在组件标签上绑定参数,通过箭头函数获取并操作参数
const Wrapper = styled.p` width: ${props => props.wrapperWidth}; height: ${({wrapperHeight}) =>parseInt(wrapperHeight)/2 + 'px'}; background: red;` (2)继承;通话styled来继承父组件的样式属性
()const ParentItem = styled.p` display: block; color: yellow; text-align: center; line-height: 1.5; font-size: 20px;`const Item = styled(ParentItem)` color: blue; font-size: 16px; &:nth-child(2n-1){ background: #00ffe4; }`{color: 'red'}}姜虎东都到曦{color: '#fff'}}郑九元 (3)操作styled组件的样式属性;可在组件标签上定义属性、也可以通过attrs定义属性
const UserInput = styled.input` display: block; width: 500px;`// 通过attr定义属性const PasswordInput = styled.input.attrs(({ type, placeholder }) => ({ type: type ? type : 'text', placeholder: placeholder || '请输入' }))` display: block;`用户名:用户:{/* 在组件标签上定义属性 */}密码:
上一篇:怎么找服务器插件信息表?
下一篇:ec服务器怎么解锁材质包?