Skip to main content

styled-component基础

CSS in js

框架的目的是减轻开发人员的开发难度,提高效率

组件化开发强制把html、js、css谢在一起

这样写有利于组件隔离,每个组件需要的代码不依赖于外部

表面上React写法是html、css、js混合写在一起,实际上是用js在写html、css,React对html的封装是jsx,对css的封装类似于styled-component

styled-component

相对于预处理器(sass、less)的好处是,css in js使用的是js语法,不用在重学习其他新技术,也不用进行预处理

npm instlal --save styled-components

基础用法

import styled from 'styled-components'

const HomeWrapper = style.div`
width: 960px;
margin: 0 auto;
overflow:hidden;
`
const HomeLeft = styled.div`
float: left;
width: 625px;
margin-left: 15px;
padding-top: 30px;
.banner-img{
width: 635px;
height: 270px;
}
`

const HomeRight = style.div`
float:right;
width:280px;
margin-left:15px;
padding-top: 30px;
`

render(){
return (
<HomeWrapper>
<HomeLeft>left</HomeLeft>
<HomeRight>right</HomeRight>
</HomeWrapper>
)
}

HomeWrapper,HomeLeft,HomeRight每个组件对应唯一的样式,不会出现样式污染的情况

全局样式

createGlobalStyle设置全局样式

import {createGlobalStyle} from 'styled-component'

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;
}
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;
}

@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;}
`
render(){
return (
<>
<Provider>...</Provider>
<GrobalStyle/>
</>
)
}

上面的代码GrobalStyle 是全局样式组件,只需在React组件的最外层引入即可

图片引入

使用import导入图片,然后以变量方式引入,如果像css一样的方式引入会报错

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;
`

props

使用组件的传值

recommendLinst.map((item)=>{
return <RecommendItem key={item} imgUrl={item}/>
})

const RecommendItem = styled.div`
width: 280px;
height: 50px;
background-image: url(${(props) => props.Url});
background-size: contain;
`

父组件传入的值,会放在子组件的props中,所以操作props能得到预期的效果

标签属性

使用styled-components需要使用标签属性,如input的placecholder,a标签的href等,styled-components提供了属性attrs

export const NavSearch = styled.input.attrs({
placeholder: '搜索',
type: 'text'
})`
width: 160px;
height: 38px;
margin-top: 9px;
padding: 0 40px 0 20px;
box-sizing: border-box;
background-color: #eee;
outline: none;
border: none;
border-radius: 19px;
color: #666;
&::placeholder{
color: #999;
}

&.focused{
width: 240px;
}
`

attrs里面是一个对象,如果需要多个属性以对象的形式添加即可

塑造组件

有一种情况一些原本就已经是组件,需要给这些组件添加样式,这时需要用到塑造组件

const Link = ({className, children}) => (
<a className={className}>
{children}
</a>
)

const StyleLink = styled(Link)`
color: palevioletred
`

render (){
<div>
<Link>普通组件</Link>
<StyledLink>添加样式的组件</StyleLink>
</div>
}

继承

如果某一组件的样式会用到多个地方,不能每个地方都重写写一套样式,这样代码不够优雅,一个button有waring、default、primary等只是颜色不同,这里可以使用继承

const Button = styled.button`
line-height: 1.499;
display: inline-block;
font-weight: 400;
text-align: center;
-ms-touch-action: manipulation;
touch-action: manipulation;
cursor: pointer;
background-image: none;
border: 1px solid transparent;
white-space: nowrap;
padding: 0 15px;
font-size: 14px;
border-radius: 4px;
height: 32px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-transition: all .3s cubic-bezier(.645,.045,.355,1);
transition: all .3s cubic-bezier(.645,.045,.355,1);
position: relative;
-webkit-box-shadow: 0 2px 0 rgba(0,0,0,.015);
box-shadow: 0 2px 0 rgba(0,0,0,.015);
color: rgba(0,0,0,.65);
background-color: #fff;
border-color: #d9d9d9;
`

const ButtonPrimary = styled(Button)`
color: #fff;
background-color: #1890ff;
border-color: #1890ff;
`

const ButtonWarning = styled(Button)`
color: #f5222d;
background-color: #f5f5f5;
border-color: #d9d9d9;
`

动画

const rotate = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;

const Rotate = styled.div`
display: inline-block;
animation: ${rotate} 2s linear infinite;
padding: 2rem 1rem;
font-size: 1.2rem;
`;

render(
<Rotate>&lt; 💅 &gt;</Rotate>
);

简单的动画,直接以这样的方式去做,即可,如果动画比较复杂,建议使用react-transition-group框架有更好的体验。

使用styled-components会随机生成一个class名称,这样不会污染到全局变量,当然因为随机生成,维护会增加难度