第一種: 在組件中直接使用style
不需要組件從外部引入css文件,直接在組件中書(shū)寫(xiě)。
import React, { Component } from "react";const div1 = { width: "300px", margin: "30px auto", backgroundColor: "#44014C", //駝峰法 minHeight: "200px", boxSizing: "border-box"};class Test extends Component { constructor(props, context) { super(props); } render() { return ( <div style={div1}>123</div> <div style="background-color:red;"> ); }}export default Test;注意事項(xiàng):
.App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white;}而在react中使用style對(duì)象的方式時(shí)。值必須用雙引號(hào)包裹起來(lái)。
這種方式的react樣式,只作用于當(dāng)前組件。
第二種: 在組件中引入[name].css文件
需要在當(dāng)前組件開(kāi)頭使用import引入css文件。
import React, { Component } from "react";import TestChidren from "./TestChidren";import "@/assets/css/index.scss";class Test extends Component { constructor(props, context) { super(props); } render() { return ( <div> <div className="link-name">123</div> <TestChidren>測(cè)試子組件的樣式</TestChidren> </div> ); }}export default Test;這種方式引入的css樣式,會(huì)作用于當(dāng)前組件及其所有后代組件。
第三種: 3、在組件中引入[name].scss文件
引入react內(nèi)部已經(jīng)支持了后綴為scss的文件,所以只需要安裝node-sass即可,因?yàn)橛袀€(gè)node-sass,scss文件才能在node環(huán)境上編譯成css文件。
>yarn add node-sass
然后編寫(xiě)scss文件
//index.scss.App{ background-color: #282c34; .header{ min-height: 100vh; color: white; }}關(guān)于如何詳細(xì)的使用sass,請(qǐng)查看sass官網(wǎng)
這種方式引入的css樣式,同樣會(huì)作用于當(dāng)前組件及其所有后代組件。
第四種: 在組件中引入[name].module.css文件
將css文件作為一個(gè)模塊引入,這個(gè)模塊中的所有css,只作用于當(dāng)前組件。不會(huì)影響當(dāng)前組件的后代組件。
import React, { Component } from "react";import TestChild from "./TestChild";import moduleCss from "./test.module.css";class Test extends Component { constructor(props, context) { super(props); } render() { return ( <div> <div className={moduleCss.linkName}>321321</div> <TestChild></TestChild> </div> ); }}export default Test;
新聞熱點(diǎn)
疑難解答
圖片精選