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)傳參;在組件標簽上綁定參數(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組件的樣式屬性;可在組件標簽上定義屬性、也可以通過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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
React中處理表單數(shù)據(jù)實現(xiàn)方式
本文介紹了如何在React中處理表單數(shù)據(jù),包括控制組件和非控制組件的使用,通過控制組件,表單的輸入值由React組件的狀態(tài)控制;非控制組件通過ref來訪問表單輸入的當前值,文章還展示了如何處理多個輸入和添加驗證和樣式,以提供更好的用戶體驗2025-02-02
react項目使用json-server模擬接口獲取數(shù)據(jù)的操作方法
文章介紹了如何在React項目中使用json-server模擬接口并獲取數(shù)據(jù),首先安裝json-server,創(chuàng)建JSON格式的數(shù)據(jù)文件,并在package.json中添加啟動命令,啟動服務后,可以通過指定的路徑獲取模擬的數(shù)據(jù),感興趣的朋友一起看看吧2025-11-11
TS裝飾器bindThis優(yōu)雅實現(xiàn)React類組件中this綁定
這篇文章主要為大家介紹了TS裝飾器bindThis優(yōu)雅實現(xiàn)React類組件中this綁定,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11

