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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值