背景
之前和現(xiàn)在寫的項目里面,有一個概念,關(guān)注點分離,也面向?qū)ο蟮某绦蛟O(shè)計的核心概念。關(guān)注點分離(Separation of concerns,SOC)是對只與“特定概念、目標”(關(guān)注點)相關(guān)聯(lián)的軟件組成部分進行“標識、封裝和操縱”的能力,即標識、封裝和操縱關(guān)注點的能力。是處理復(fù)雜性的一個原則。由于關(guān)注點混雜在一起會導(dǎo)致復(fù)雜性大大增加,所以能夠把不同的關(guān)注點分離開來,分別處理就是處理復(fù)雜性的一個原則,一種方法。
所以關(guān)注點分離概念在前端開發(fā)的領(lǐng)域,就是把html、css、JavaScript分開成三大獨立部分,各自解耦,降低復(fù)雜度,也更好的維護。
簡單說,就是不要寫“行內(nèi)樣式”和“行內(nèi)腳本”。
React和模塊化概念的出現(xiàn)
React和jsx的出現(xiàn),改變了獨立三個部分的局面,html寫到j(luò)s里面成為了jsx,頁面也被切分成一個個模塊,這時候?qū)ss來說,獨立打包似乎并不是那么的理所當然了,似乎一個模塊有它自己的html、js、css才是更好的切分頁面功能的方式。
CSS in JS
React其實也不是不寫html了,只是用JavaScript來寫html,所以css是不是也能用JavaScript來寫?
答案是肯定的。而且還有很多庫,包裝了非常多的便利的方法。這里舉個最近在看的庫為例子:Polished。
Installation
$ npm install --save polished
Usage
import { lighten, modularScale } from 'polished'
Example
取一個方法做一個實例:
clearFix
// Styles as object usage
const styles = {
...clearFix(),
}
// styled-components usage
const div = styled.div`
${clearFix()}
`
// CSS as JS Output
'&::after': {
'clear': 'both',
'content': '""',
'display': 'table'
}
ellipsis
// Styles as object usage
const styles = {
...ellipsis('250px')
}
// styled-components usage
const div = styled.div`
${ellipsis('250px')}
`
// CSS as JS Output
div: {
'display': 'inline-block',
'maxWidth': '250px',
'overflow': 'hidden',
'textOverflow': 'ellipsis',
'whiteSpace': 'nowrap',
'wordWrap': 'normal'
}
方法有很多,羅列如下就是:
Mixins
clearFix
ellipsis
fontFace
hiDPI
hideText
hideVisually
normalize
placeholder
radialGradient
retinaImage
selection
timingFunctions
triangle
wordWrap
Color
adjustHue
complement
darken
desaturate
getLuminance
grayscale
hsl
hsla
invert
lighten
mix
opacify
parseToHsl
parseToRgb
readableColor
rgb
rgba
saturate
setHue
setLightness
setSaturation
shade
tint
transparentize
Shorthands
animation
backgroundImages
backgrounds
borderColor
borderRadius
borderStyle
borderWidth
buttons
margin
padding
position
size
textInputs
transitions
Helpers
directionalProperty
em
modularScale
rem
stripUnit
Types
AnimationProperty
FontFaceConfiguration
HslColor
HslaColor
InteractionState
PointingDirection
RadialGradientConfiguration
Ratio
RgbaColor
RgbColor
TimingFunction
toColorString
ModularScaleRatio
方法足夠多,從名稱上來看也知道是干嘛的了。使用起來也很方便。嘗試一下,也許會帶來不一樣的思維模式。
寫在最后
CSS in JS都有了,那CSS預(yù)處理語言SASS/LESS該怎么辦?蘿卜白菜各有所愛,也不是說誰一定會取代誰,適合自己的才是最好的。
前端,在造輪子的路上,越走越遠。