React中引用CSS方式及寫法大全(三種方式)
更新時間:2023年10月17日 08:27:07 作者:我只會寫B(tài)ug啊
在React中引用CSS的方法有多種,可以根據(jù)個人的喜好和項目的需求來選擇,本文主要介紹了React中引用CSS方式及寫法大全,感興趣的可以了解一下
引用方式
第一種:內(nèi)聯(lián)方式
可以使用變量或者傳統(tǒng)的內(nèi)聯(lián)方式
優(yōu)點: 只生效于當(dāng)前組件
缺點: 可能產(chǎn)生大量重復(fù)代碼
import react, { Component } from "react";
const sty = {
width: "100px",
backgroundColor: "#FFFFFF", //注意:需要使用駝峰法
boxSizing: "border-box"
};
class Test extends Component {
constructor(props, context) {
super(props);
}
render() {
return (
<div style={sty}>123</div>
<div style="background-color:red;">
);
}
}
export default Test;
第二種:在組件引用 [name] .css文件
優(yōu)點: 復(fù)用性強
缺點: 存在樣式覆蓋問題,不是只生效于當(dāng)前組件
import React, { Component } from "react";
import TestChidren from "./TestChidren";
import "@/assets/css/index.scss";
// styName寫在 "/assets/css/index.scss" 中即可
class Test extends Component {
constructor(props, context) {
super(props);
}
render() {
return (
<div>
<div className="styName">123</div>
<TestChidren>測試子組件的樣式</TestChidren>
</div>
);
}
}
export default Test;
第三種:在組件中引用[name] .scss文件
安裝node-sass就可以,因為有個node-sass,scss文件才能在node環(huán)境上編譯成css文件。
然后編寫scss文件
.App{
background-color: #282c34;
.header{
min-height: 100vh;
color: white;
}
}
第四種:在組件中引用[name].module.css文件
優(yōu)點: 可實現(xiàn)CSS的局部作用域,并且可復(fù)用
重點:
1、選擇器駝峰命名
2、樣式文件后綴名為.module.css
3、在js文件中導(dǎo)入并使用
注:
1、css modules會默認給類名加上一個唯一標(biāo)識符(哈希字符串),從而實現(xiàn)類名不重復(fù)
2、class名稱需要使用駝峰命名,不支持 '-' 等連接符
命名規(guī)則: xxx.module.css
引入方式:import xxx from 'xxx.module.css'
用法:<div className={xxx.styleName}>
寫法
三種內(nèi)聯(lián)寫法
class App extends PureComponent{
constructor(props) {
super(props);
/* 動態(tài)改變元素樣式 */
this.state = {
textColor:"pink"
}
}
render(){
/* 將樣式抽取到一個變量中 */
const h2Style={
fontSize:"18px",
color:"red"
}
return(
<div>
<h2 style={h2Style}>這是一個App組件</h2>
<p style={{fontSize:"18px",color:"red"}}>這是一段文字</p>
<div style={{color:this.state.textColor}}>這是一段動態(tài)變化的文字</div>
</div>
)
}
}
三元表達式
<div>
<h2 className={"title " + (isActive ? "active": "")}>內(nèi)容</h2>
<h2 className={["title", (isActive ? "active": "")].join(" ")}>內(nèi)容</h2>
</div>
引用module.css
import appStyle from "./style.module.css";
import common from "./common.module.css";
// 單個class
<h2 className={appStyle.title}>
內(nèi)容
</h2>
// 多個class
<div className={appStyle.box6 + ' ' + common.flexRow + ' ' + common.justifyBetween}>
內(nèi)容
</div>到此這篇關(guān)于React中引用CSS方式及寫法大全(三種方式)的文章就介紹到這了,更多相關(guān)React 引用CSS內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
react 不用插件實現(xiàn)數(shù)字滾動的效果示例
這篇文章主要介紹了react 不用插件實現(xiàn)數(shù)字滾動的效果示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
詳解react-router 4.0 下服務(wù)器如何配合BrowserRouter
這篇文章主要介紹了詳解react-router 4.0 下服務(wù)器如何配合BrowserRouter,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12

