寫在前面
食用此文檔需要你至少具備
- 基礎(chǔ)的css使用
- 基礎(chǔ)的JavaScript使用
- 基礎(chǔ)的react的使用
在React還未出現(xiàn)的時(shí)候, 網(wǎng)頁(yè)開發(fā)有一個(gè)原則叫做關(guān)注點(diǎn)分離
(正交原則
)
關(guān)注點(diǎn)分離
首先看一下百度百科的解釋
關(guān)注點(diǎn)分離(Separation of concerns,SOC)是對(duì)只與“特定概念禾蚕、目標(biāo)”(關(guān)注點(diǎn))相關(guān)聯(lián)的軟件組成部分進(jìn)行“標(biāo)識(shí)、封裝和操縱”的能力,即標(biāo)識(shí)摇零、封裝和操縱關(guān)注點(diǎn)的能力。是處理復(fù)雜性的一個(gè)原則。由于關(guān)注點(diǎn)混雜在一起會(huì)導(dǎo)致復(fù)雜性大大增加痢畜,所以能夠把不同的關(guān)注點(diǎn)分離開來(lái)敛熬,分別處理就是處理復(fù)雜性的一個(gè)原則肺稀,一種方法。
通俗易懂的說(shuō)就是, HTML, css, JavaScript 分離, 不要混到一起用, 不要寫 行內(nèi)樣式
和 行內(nèi)腳本
, 比如下面的代碼就很糟糕
<h1 style="color:red;font-size:46px;" onclick="alert('Hi')">
Hello World
</h1>
正確的做法是分為三個(gè)部分, 分別寫html/css/javaScript
<h1 calss="title">
Hello World
</h1>
.title {
color: red;
font-size: 46px;
}
const titleDom = document.querySelector('.title');
titleDom.addEventListener('click', sayHi);
function sayHi() {
alert('Hi');
}
React 的出現(xiàn)
React
出現(xiàn)以后, 這個(gè)原則不再適用了应民。 因?yàn)?code>React是組件結(jié)構(gòu), 強(qiáng)制要求把 HTML话原、CSS、JavaScript 寫在一起诲锹。
上面的例子使用 React 改寫如下
const style = {
'color': 'red',
'fontSize': '46px'
};
const clickHandler = () => alert('hi');
ReactDOM.render(
<h1 style={style} onclick={clickHandler}>
Hello, world!
</h1>,
document.getElementById('example')
);
上面代碼在一個(gè)文件里面繁仁,封裝了結(jié)構(gòu)、樣式和邏輯归园,完全違背了"關(guān)注點(diǎn)分離"的原則黄虱。
但是,這有利于組件的隔離庸诱。每個(gè)組件包含了所有需要用到的代碼捻浦,不依賴外部,組件之間沒(méi)有耦合桥爽,很方便復(fù)用默勾。所以,隨著 React 的走紅和組件模式深入人心聚谁,這種關(guān)注點(diǎn)混合
的新寫法逐漸成為主流母剥。
css in js
由于React的出現(xiàn), 使得關(guān)注點(diǎn)混合
的新寫法逐漸成為主流, 但由于React對(duì)css的封裝非常弱, 導(dǎo)致了一系列第三方庫(kù), 用來(lái)加強(qiáng)React
的 css操作, 也就是說(shuō)css in js 技術(shù)僅僅適用于關(guān)注點(diǎn)混合的結(jié)構(gòu)
由于只要是加強(qiáng)JavaScript 對(duì) css 的操作就可以稱為css in js
, 因此css in js
并沒(méi)有統(tǒng)一的實(shí)現(xiàn)方式, 如果你要挑選css in js
類庫(kù), 可以在MicheleBertoli/css-in-js中找你喜歡的庫(kù), 這里收集了大量使用較多的css in js
庫(kù)
下面介紹一款css in js
類庫(kù)的使用
Aphrodite
目前排名第一的是 Aphrodite 這個(gè)類庫(kù),這里我寫了一個(gè)Aphrodite的在線模板, 可以直接在上面練習(xí)
先來(lái)看一下基礎(chǔ)用法
import React from "react";
import ReactDOM from "react-dom";
import { StyleSheet, css } from "aphrodite";
// 創(chuàng)建樣式
const styles = StyleSheet.create({
red: { color: "red" }
});
ReactDOM.render(
// 載入樣式
<div className={css(styles.red)}>
<h1>Hello aphrodite!</h1>
</div>,
document.getElementById("root")
);
既然是用JS來(lái)控制CSS, 就可以用條件判斷來(lái)容易的控制樣式
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { StyleSheet, css } from "aphrodite";
// 創(chuàng)建樣式
const styles = StyleSheet.create({
red: { color: "red" },
green: { color: 'green' }
});
class App extends Component {
constructor(props) {
super(props);
this.state = { isGreen: false };
this.handleClick = this.handleClick.bind(this);
}
/**
* 點(diǎn)擊事件, 用來(lái)切換紅色與綠色
*/
handleClick() {
this.setState({
isGreen: !this.state.isGreen,
});
}
/**
* 獲取組件樣式表
*/
getClassName() {
const { isGreen } = this.state;
const titleClassName = css(isGreen ? styles.green : styles.red);
return { titleClassName };
}
render() {
const { handleClick } = this;
const { titleClassName } = this.getClassName();
return (
<div className={titleClassName}>
<h1>Hello aphrodite!</h1>
<button onClick={handleClick}>
change
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Aphrodite默認(rèn)所有的樣式都增加了 !important 如果不想要這個(gè)特性, 可以引入aphrodite/no-important
import { StyleSheet, css } from 'aphrodite/no-important';
除了以上基礎(chǔ)用法, Aphrodite還提供了minify
函數(shù), 用來(lái)壓縮css
import { StyleSheet, minify } from 'aphrodite';
minify(true);
Aphrodite還可以在非react的環(huán)境下使用, 但不推薦這樣做, 這里不做示例了
另外使用Aphrodite還要注意, 在獲取元素屬性時(shí), 需要做一下延時(shí), 因?yàn)锳phrodite不能確保設(shè)置的元素樣式會(huì)立即生效
Style injection and buffering
Aphrodite will automatically attempt to create a <style> tag in the document's <head> element to put its generated styles in. Aphrodite will only generate one <style> tag and will add new styles to this over time. If you want to control which style tag Aphrodite uses, create a style tag yourself with the data-aphrodite attribute and Aphrodite will use that instead of creating one for you.To speed up injection of styles, Aphrodite will automatically try to buffer writes to this <style> tag so that minimum number of DOM modifications happen.
Aphrodite uses asap to schedule buffer flushing. If you measure DOM elements' dimensions in componentDidMount or componentDidUpdate, you can use setTimeout or flushToStyleTag to ensure all styles are injected.
自己封裝一個(gè)css in js 庫(kù)
看了一些示例之后我自己也試著封裝了一個(gè)css in js庫(kù), 有興趣的同學(xué)可以看源碼
在線示例
大致思路參考
首先將傳入的data, 例如
const data = {
app: {
fontFamily: "sans-serif",
textAlign: "center"
}
}
解析成
{
className: 'app',
id: 'cssInJs0',
style: { ... },
}
將解析后的數(shù)據(jù)轉(zhuǎn)成style標(biāo)簽
并置入head標(biāo)簽
中, 解析完成如下
<style>.cssInJs0.app{font-family:sans-serif;text-align:center;}</style>
將類名暴露出去, 并暴露一個(gè)方法css
, 作用就是自動(dòng)拼接className
, 并去重
<div className={css(sty.app)}></div>
使用css
解析出的className
<div class="cssInJs0 app"></div>
以上 ~