css-in-js
react是用js寫html的框架,爲了在react框架中使用js編寫一切代碼,使用css-in-js庫編寫css代碼,style-components是近期使用人數最多的css-in-js庫,它的優點如下:
- 可以編寫實際的CSS代碼來設計組件樣式,也不需要組件和樣式之間的映射,即創建後就是一個正常的React 組件,直接在JSX中引入即可
- 在一個組件內會將結構、樣式和邏輯寫在一起,雖然這違背了關注點分離的原則,但是這有利於組件間的隔離。爲了順應組件化的潮流
- 使用styled-components不需要再使用className屬性來控制樣式,而是將樣式寫成更具語義化的組件的形式
- 使用style-components會隨機生成一個class名稱,這樣不會污染到全局變量,當然因爲隨機生成,維護會增加難度
1.基礎用法
給div增加樣式,生成一個組件,這個組件對應唯一的樣式,編譯過後會自動給<Wrapper>
對應的元素添加一個自動命名的類名<div class='abc-feg'>
。
import styled from 'styled-components';
const Wrapper = styled.div `
width: 960px;
height: 500px;
background: red;
margin: 0 auto;
`;
render () {
return (
<Wrapper>
<p>基礎用法</p>
</Wrapper>
)
}
2.全局樣式
爲了避免瀏覽器默認樣式的影響,需要格式化全局樣式,style-components提供了全局樣式設置,設置過全局樣式之後再添加某元素就是全局樣式中的樣式了。
import { createGlobalStyle } from 'styled-components';
// 全局樣式設置,消去瀏覽器默認樣式的影響
// 相當於把全局樣式當成一個組件導出
export const GlobalStyle = createGlobalStyle`
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
html, body {
background: #4DB3B3;;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
a {
text-decoration: none;
color: #fff;
}
// 字體圖標的unicode編碼
@font-face {
font-family: 'iconfont'; /* project id 897264 */
src: url('//at.alicdn.com/t/font_897264_7ma62sn10m3.eot');
src: url('//at.alicdn.com/t/font_897264_7ma62sn10m3.eot?#iefix') format('embedded-opentype'),
url('//at.alicdn.com/t/font_897264_7ma62sn10m3.woff') format('woff'),
url('//at.alicdn.com/t/font_897264_7ma62sn10m3.ttf') format('truetype'),
url('//at.alicdn.com/t/font_897264_7ma62sn10m3.svg#iconfont') format('svg');
}
// 設置字體圖標的大小
.iconfont {
font-family:"iconfont" !important;
font-size:16px;
font-style:normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.clearfix:after {visibility: hidden;display: block;font-size: 0;content: ".";clear: both;height: 0;}
.clearfix {zoom: 1;}
`
// JSX中引入
render() {
return (
<div>
<GrobalStyle/>
<Wrapper>
<p>基礎用法</p>
{ /* 引入菜單圖標 */ }
<span className = 'iconfont menu'></span>
</Wrapper>
<div>
)
}
3.引入圖片
需要圖片引入,如果像css一樣的引入方式,會報錯。正確的引入方式是import導入,再以變量的方式引入,如下:
import styled from 'styled-components';
import logPic from '../../statics/images/logo.png';
export const Logo = styled.div `
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 56px;
background-image: url(${logPic});
background-size: contain;
`;
4.還可以用組件的props傳值
recommendList.map((item) => {
return <RecommendItem key={item} imgUrl={item}/>
})
const RecommendItem = styled.div `
width: 280px;
height: 50px;
background-image: url(${(props) => props.imgUrl});
background-size: contain;
`;
5.塑造組件
給react定義過的組件添加樣式,注意給組件添加樣式跟元素標籤的不同,組件是styled(Component)
,元素標籤是styled.tagname
// 定義組件,這個組件就是普通組件,本來取決於a的樣式
const Link = ({className , children}) => (
<a className={className}>
{children}
</a>
)
// 給這個組件添加樣式
const StyledLink = styled(Link)`
color: palevioletred;
`
render(
<div>
<Link>普通組件</Link>
<StyledLink>添加了樣式的組件</StyledLink>
</div>
);
6.選擇器
在styled-components中也可以使用css選擇器、僞元素、媒體查詢以及各類的聲明樣式。
- 標籤名選擇器、類選擇器、僞類和僞元素跟css中是一樣的
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>
)
- 後代選擇器,要表示出嵌套關係需要使用
&
符號表示引用主組件
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>
{/* red要在Thing的包裹元素中才能使用 */}
<Thing>
<p className="red" >p標籤</p>
</Thing>
</React.Fragment>
)
- 上下文選擇器
const Thing = styled.div`
/* 應用於緊鄰Thing組件的下一個Thing組件 */
& + & {
color: red;
}
`
render(
<React.Fragment>
<Thing>第一個Thing組件 默認顏色</Thing>
<Thing>第二個Thing組件 紅色</Thing>
</React.Fragment>
)
7.繼承
// 用.extend 創建一個新的StyledComponent並且繼承它的規則,可添加或覆蓋屬性
const NewButton = Button.extend`
color: tomato;
border-color: tomato;
`;
// .withComponent 應用其他組件或標籤的樣式到自己身上
const Link = Button.withComponent('a')