React引入css的幾種方式及應(yīng)用小結(jié)
1.直接引入css文件
import "./parent.css"
2.引入css模塊,定義文件名[組件名.module.css];該方式可避免類名的重復(fù),每個組件都有獨立的作用域,避免了全局污染,保證了類名的唯一性
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.應(yīng)用
(1)傳參;在組件標(biāo)簽上綁定參數(shù),通過箭頭函數(shù)獲取并操作參數(shù)
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組件的樣式屬性;可在組件標(biāo)簽上定義屬性、也可以通過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> {/* 在組件標(biāo)簽上定義屬性 */} 密碼:<PasswordInput value={this.state.password} type="password" placeholder="請輸入密碼"></PasswordInput>
到此這篇關(guān)于React引入css的幾種方式以及應(yīng)用的文章就介紹到這了,更多相關(guān)React引入css內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ReactNative點擊事件.bind(this)操作分析
這篇文章主要為大家介紹了ReactNative點擊事件.bind(this)操作分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11react反向代理使用http-proxy-middleware問題
這篇文章主要介紹了react反向代理使用http-proxy-middleware問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07Next+React項目啟動慢刷新慢的解決方法小結(jié)
本文主要介紹了Next+React項目啟動慢刷新慢的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-04-04關(guān)于React Native報Cannot initialize a parameter of type''NSArra
這篇文章主要介紹了關(guān)于React Native報Cannot initialize a parameter of type'NSArray<id<RCTBridgeModule>>錯誤,本文給大家分享解決方案,需要的朋友可以參考下2021-05-05React?Hooks之usePolymerAction抽象代碼結(jié)構(gòu)設(shè)計理念
這篇文章主要為大家介紹了React?Hooks之usePolymerAction抽象代碼結(jié)構(gòu)設(shè)計理念,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09React中實現(xiàn)組件通信的幾種方式小結(jié)
在構(gòu)建復(fù)雜的React應(yīng)用時,組件之間的通信是至關(guān)重要的,從簡單的父子組件通信到跨組件狀態(tài)同步,不同組件之間的通信方式多種多樣,下面我們認(rèn)識react組件通信的幾種方式,需要的朋友可以參考下2024-04-04