在react項目中,直接引入樣式檔案會影響到全局樣式,并非獨立的。
解決方法有五種:
1、行内樣式(react官網推薦)
class App extends React.Component {
// ...
render() {
return (
<div style={{ background: '#eee', width: '200px', height: '200px'}}>
<p style= {{color:'red', fontSize:'40px'}}>行内樣式</p>
</div>
)
}
}
2、聲明樣式
class App extends React.Component {
//...
const style1={
background:'#eee',
width:'200px',
height:'200px'
}
const style2={
color:'red',
fontSize:'40px'
}
render() {
return (
<div style={style1}>
<p style= {style2}>行内樣式</p>
</div>
)
}
}
3、開啟css modules功能
相關教程:
作者:阮一峰
連結(css modules用法教程):http://www.ruanyifeng.com/blog/2016/06/css_modules.html
4、利用第三方工具Styled Components
具體使用在此不詳述。
個人推薦第一種方法與第三種方法,即行内樣式與css modules結合的方式。下面接着上一章的《webpack項目初始配置(一)》中的内容,配置webpack.config.js檔案,因為新手爬坑過程中,很容易遇到開啟了css modules功能之後,antd預設的樣式就不生效的問題。
//css的處理,開啟css modules功能,node_modules庫中的antd樣式除外
{
test: /\.css$/,
exclude: /node_modules|antd\.css/,
use: ExtractTextPlugin.extract({
fallback:'style-loader',
use: "css-loader?modules&localIdentName=styles__[local]__[hash:base64:5]"
}),
},
//css的處理,node_modules庫中的antd樣式不開啟css modules功能,但還是要編譯的
{
test: /\.css$/,
include: /node_modules|antd\.css/,
use: ExtractTextPlugin.extract({
fallback:'style-loader',
use: "css-loader"
})
},
//這裡開啟自己編寫的less檔案的css modules功能,除了node_modules庫中的less
//也就是可以過濾掉antd庫中的樣式
{
test: /\.less$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader?modules&localIdentName=styles__[local]__[hash:base64:5]",
{
loader: 'less-loader', options: {modifyVars: theme}
}
]
})
},
//less的處理,需要加入node_modules裡面的樣式,并且不開啟css modules功能
{
test: /\.less$/,
include: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ["css-loader",
{
loader: 'less-loader', options: {modifyVars: theme}
}
]
})
},
關鍵代碼說明:
//開啟css modules之前的代碼
use: "css-loader"
//開啟css modules之後的代碼
use: "css-loader?modules&localIdentName=styles__[local]__[hash:base64:5]
// ?modules 是開啟css_modules
// localIdentName定義哈希字元串的格式
效果:
引入樣式:
定義樣式index.less:
網頁編譯後: