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內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
ReactNative點擊事件.bind(this)操作分析
這篇文章主要為大家介紹了ReactNative點擊事件.bind(this)操作分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11
react反向代理使用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-05
React?Hooks之usePolymerAction抽象代碼結構設計理念
這篇文章主要為大家介紹了React?Hooks之usePolymerAction抽象代碼結構設計理念,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09

