本文講解一些styled-components
的基本使用方法,主要講由styled-components
生成的樣式組件里面的html
標簽的樣式是如何寫的。找了一圈發現中文社區里目前還沒有我想講的這一部分的內容,但是這部分內容又是相當基礎且重要的。所以現在我們就一起來學習一下吧。
本文的大部分內容都是我從官方文檔里翻譯來的,有興趣的同學看完文章后可以移步官方文檔,我這里只起一個拋磚引玉的作用。
安裝
npm install --save styled-components
最基礎的用法
在下面這個例子中,我們用styled-components
創建了一個樣式組件,該組件渲染之后是一個div
標簽。注意組件首字母必須大寫不然無法識別。
/* 創建了一個Wrapper樣式組件,該組件渲染之后是一個div標簽 */
const Wrapper = styled.div`
color: blue;
`;
/* Wrapper組件跟其余的react組件一樣,只不過現在他們有了自己的樣式 */
render(
<Wrapper>
Hello World!
</Wrapper>
);
渲染結果如下:
styled-components-2-1.jpg
選擇器:標簽名和類名
我們可以通過標簽名和類名設置樣式組件中的html
標簽的樣式:
const Wrapper = styled.div`
/* 應用於Wrapper組件本身和Wrapper組件里的所有html標簽 */
color: black;
/* 應用於Wrapper組件里的h3標簽 */
h3 {
color: red
}
/* 應用於Wrapper組件里的className為blue的html標簽 */
.blue {
color: blue
}
`
render(
<Wrapper>
<p>黑色 p 標簽 </p>
<h3>紅色 h3 標簽</h3>
<p className="blue" >藍色 p 標簽</p>
</Wrapper>
)
渲染結果如下:
styled-components-2-2.jpg
選擇器:偽類和偽元素
在styled-components
同樣可以使用偽類和偽元素,使用方法和原生css
一模一樣:
const Thing = styled.button`
color: blue;
::before {
content: '!!!';
}
:hover {
color: red;
}
`
render(
<Thing>Hello world!</Thing>
)
渲染結果如下:
styled-components-2-3.gif
嵌套
&
符號表示引用主組件,注意體會加上&
符號與不加的區別:
const Thing = styled.div`
/* 應用於className為blue的Thing組件 */
&.blue{
color: blue;
}
/* 應用於className為red的Thing組件里的所有子組件或者html標簽 */
.red {
color: red;
}
`
render(
<React.Fragment>
<Thing className="blue" >Thing組件</Thing>
<Thing>
<p className="red" >p標簽</p>
</Thing>
</React.Fragment>
)
渲染結果如下:
styled-components-2-4.jpg
上下文選擇符
在styled-components
同樣可以使用各類上下文選擇符:
const Thing = styled.div`
/* 應用於緊鄰Thing組件的下一個Thing組件 */
& + & {
color: red;
}
`
render(
<React.Fragment>
<Thing>第一個Thing組件</Thing>
<Thing>第二個Thing組件</Thing>
</React.Fragment>
)
渲染結果如下:
styled-components-2-5.jpg
通過這幾個例子可以看出來,styled-components
中的css
寫法和原生的css
寫法其實差別並不大。而今天剛剛介紹的其實這些僅僅是styled-components
的冰山一角。基於react
的組件化思想,用styled-components
對樣式也進行了組件化,這樣每個組件擁有了自己的功能,還擁有了自己的樣式,從而能夠實現真正意義上的復用。react
通過state
來控制組件,而styled-components
也可以通過state
的改變來動態的改變組件的樣式。react
和styled-components
可以說是男才女貌了。
想要了解更多styled-components
知識還是希望大家能夠去閱讀她的官方文檔。