react中通過jsx的語法方式,將html標簽和js語法聯系在一起,而css的編寫方式,沒有明確的指定編寫方式,目前就有很多不同方法,每個方式各有其優缺點,我們一起來看看常用的定義方式有哪些。
最基礎也是最簡單的方式就是如html當中編寫樣式一樣,直接內聯使用,區別在於jsx中內聯使用樣式需要用小駝峰命名,不可使用短橫線 -,jsx中編寫js的表達式需要使用 {},而定義的樣式是以對象的形式存在,也是通過{},所以看起來style標簽里面使用了兩個大括號{}
return(<div style={{color: 'blue'}}> hello react </div>)
return(<div className="title"> hello react </div>) // 定義在單獨的樣式文件 .title { color: 'blue' }
當需要使用多個className,或者通過狀態來變更className時,可以通過+來進行字符串拼接,或者使用數組,再通過toString()轉成字符串
const isActive = true <h2 className="active foo bar">我是標題1</h2> // active foo bar <h2 className={"foo", (isActive ? "active" : "") }>我是標題2</h2> // active <h2 className={"foo" + (isActive ? " active" : "") }>我是標題3</h2> // foo, active <h2 className={["foo",(isActive ? "active" : "")]}>我是標題4</h2> // foo, active <h2 className={["foo",(isActive ? "active" : "")].join(" ")}>我是標題5</h2> // foo avtive
為了解決這一問題,我們就需要在跟標簽處再定義一個className,來包裹當前組件的所有標簽,這樣css樣式的層級就比較多,並且還可能因為選擇器優先級的問題(在外層定義了id選擇器),而產生樣式沖突,同時它不支持獲取state屬性動態設置樣式。
return(<div className="homeComponent">
<div className="title">hello react</div>
</div>)
此時就產生了第三種編寫方式,css的模塊化,這樣的方式可以區分各個組件的樣式,不會相互覆蓋,而且還能定義偽類,react腳手架當中內置了css modules的配置,我們可以直接將css的文件定義為 xxx.module.css,在xxx.module.css文件中,還是按照以前的css編寫方式編寫,不同點在於jsx頁面中定義className,先引入該css文件,然后定義類名以對象的形式定義
這樣一種定義樣式的方式能夠比較有效的解決樣式重疊的問題,麻煩之處就是每次編寫樣式的時候需要通過對象的語法來定義,並且不支持動態的設置樣式。
那么就有了第四種方式,css in js,這是一種代碼的理念,react中html和js沒有分離,那么css也可以不分離,以js的方式來編寫css,使css的編寫更加的靈活,既可以像之前寫css一樣編寫,又可以動態的獲取屬性。這種編寫方式需要依賴其它庫,這里使用常用的 styled-components來演示。
使用 styled-components之前需要對es6模板字符串的一種語法有了解,我們可以使用模板字符串來對字符串和屬性進行拼接,在此之前的拼接可能都需要使用 +
const name = 'kiki' const age = '18' const user = `my name is ${name}, age is ${age}` console.log(user) // my name is kiki, age is 18
let name = 'kiki', age = 18 function foo(...args){ console.log(args) } foo`hello` foo`my name is ${name}, age is ${age} `
import React, { PureComponent } from 'react' import styled from 'styled-components' const DivStyle = styled.div` background-color: gray; color: #fff; font-size: 20px; ` export default class Profile extends PureComponent{ render(){ return(<div> <DivStyle>我是Profile組件的內容</DivStyle> </div>) } }
import React, { PureComponent } from 'react' import styled from 'styled-components' const InputStyle = styled.input.attrs({ type: 'text', placeholder: '請輸入內容', })` color: ${props => props.color} ` export default class Deliver extends PureComponent{ constructor(props){ super(props) this.state = { color: 'purple' } } render(){ return(<p> <InputStyle type="password" color={this.state.color}/> </p>) } }
以上四種樣式在react當中的定義方式是比較常用的,可以根據情況結合使用~