react開發中組件時,當樣式比較簡單時,可是使用行內樣式寫,如<div style={{color:'red'}}></div>去描述你的樣式,當react專案比較龐大,組件繁瑣時采用行內樣式顯得不適合,這部我們會想到外部樣式,
react中的外部樣式
像寫css工程一樣,定義一個css樣式檔案,在組件中import引入寫好的樣式,
// text.css檔案如下
.text1{color:red}
.text2{color:green}
將css檔案引入你的組件工程,如在demo1組件中使用:
import './text.css';//組件引入定義好的css
//使用樣式
return (
<div className='container'>
<div className='text1'>樣式一</div>
<div className='text2'>樣式二</div>
</div>
)
外部樣式在整個工程中,雖然可讀性好,但容易引起類的全域全域污染,命名沖突也會參考其他地方的樣式,這可能不是開發者不想要的效果,為了解決樣式全域污染,可以使用模塊化的樣式,
react中的css module
在src檔案夾新建一個text.module.css的檔案,如:
// text.module.css檔案如下
.text1{color:red}
.text2{color:green}
組件模塊中這么去使用:
import style from './text.css';//組件引入定義好的css
//使用樣式
return (
<div className='container'>
<div className={style.text1}>樣式一</div>
<div className={style.text2}>樣式二</div>
</div>
)
css模塊的參考分同一個模塊中參考和不同模塊中參考,在同一個模塊中參考,使用關鍵字compose完成,如定義公共的文字樣式,在其他類中使用:
// text.module.css檔案如下
.common{
text-decoration:underline;
text-indent:2em;
}
.text1{
color:red;
composes:common;
}
.text2{color:green}
上述類text1就完成了同一個檔案中不同模塊的參考,使用class為text1就擁有了common的樣式,當工程變得越來越復雜時,采用不同模塊中使用的方式,公共樣式檔案比較龐大,可以提取,新建問價common.module.css檔案夾,里面撰寫公共代碼,在text.module.css中還是使用compose關鍵字參考,如下所示:
// text.module.css檔案如下
.text1{
color:red;
composes:common from './common.module.css';
}
.text2{color:green}
css管理工具
css module在實際react開發的場景中,可能還是不能高效的支撐開發,本文介紹兩種工具支撐react中css module的開發,分別是styled-component和classnames,
本節僅描述第三方classnames是如何支撐css module高效開發的,styled-component感興趣的可以進入其官網學習,
首先通過npm 命令在本地react工程中安裝npm i classnames --save;
安裝完成后在組件中import進來使用
import style from './text.module.css';//引入css模塊
import classnames from 'classnames/bind'//引入classnames
const cls=classnames.bind();//使用bind方法
//使用樣式
return (
<div className='container'>
<div className={cls('text1 text2')}>樣式一</div>
<div className={style.text2}>樣式二</div>
</div>
)
上述使用工具classnames與不使用的效果一目了然,使用classnames可以像我們正常寫dom那樣,使用字串的形式添加類,字串中后面的類仍然可以覆寫前面的類,如text2中的文字顏色可以覆寫text1的文字顏色,
本文簡單的介紹下react中css的解決方案,通過css module優化工程,提高開發效率,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/247696.html
標籤:其他
下一篇:掃雷,C++【低配版】
