React引入css的几种方式及应用小结
1.直接引入css文件
import "./parent.css"
2.引入css模块,定义文件名[组件名.module.css];该方式可避免类名的重复,每个组件都有独立的作用域,避免了全局污染,保证了类名的唯一性
import styles from "./parent1.module.css" .title{ color: red; } <h2 className={styles.title} style={{ background:'pink' }}>我是父组件</h2>
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 ` <StyleTitle>第三方库引入css demo</StyleTitle> <StyleP>第三方库引入css demo</StyleP>
4.应用
(1)传参;在组件标签上绑定参数,通过箭头函数获取并操作参数
const Wrapper = styled.div` width: ${props => props.wrapperWidth}; height: ${({wrapperHeight}) =>parseInt(wrapperHeight)/2 + 'px'}; background: red; ` <Wrapper wrapperWidth="200px" wrapperHeight="100px"></Wrapper>
(2)继承;通话styled来继承父组件的样式属性
const ParentItem = styled.div` 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; } ` <ParentItem style={{color: 'red'}}>姜虎东</ParentItem> <Item>都到曦</Item> <Item style={{color: '#fff'}}>郑九元</Item>
(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; ` 用户名:<UserInput value={this.state.username} type="text" placeholder="请输入用户名"></UserInput> 用户:<PasswordInput value={this.state.username}></PasswordInput> {/* 在组件标签上定义属性 */} 密码:<PasswordInput value={this.state.password} type="password" placeholder="请输入密码"></PasswordInput>
到此这篇关于React引入css的几种方式以及应用的文章就介绍到这了,更多相关React引入css内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
ReactNative点击事件.bind(this)操作分析
这篇文章主要为大家介绍了ReactNative点击事件.bind(this)操作分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-11-11react反向代理使用http-proxy-middleware问题
这篇文章主要介绍了react反向代理使用http-proxy-middleware问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-07-07关于React Native报Cannot initialize a parameter of type''NSArra
这篇文章主要介绍了关于React Native报Cannot initialize a parameter of type'NSArray<id<RCTBridgeModule>>错误,本文给大家分享解决方案,需要的朋友可以参考下2021-05-05React Hooks之usePolymerAction抽象代码结构设计理念
这篇文章主要为大家介绍了React Hooks之usePolymerAction抽象代码结构设计理念,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-09-09
最新评论