styled-components,
这次一定会!
产生原因
用js写所有的趋势
react致力于用js写所有html以及逻辑相关的代码部分,既然如此,何不用js写css控制组件样式呢? styled-components顺势而生
巨巨巨好用!!!
- 通过style构建元素节点会自动在外层包裹一个加密类!
- 太多类名记不住?一不小心就样式覆盖了?快用styled-components!
- 不用引入stylesheet
- 即写即用!无脑类名!当页享受!
- 妈妈再也不用担心我样式覆盖啦——!
- 我太快乐了!!大家快去上手!!就这么看看真的体会不到他的好处!!
请一定要看到最后!!最后有小惊喜!
这个代码要有装一个插件才能高亮哦!
快速上车
基本用法
const componentsName=styled.tagname`[css写法]`
类似模板字符串
//一个名为title的组件其会render一个style如模板字符串的h1 tag
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
render(
<Wrapper>
<Title>
Hello World!
</Title>
</Wrapper>
);
根据props拓展
- 由于类似模板字符串所以可以想见会有这种拓展方式
const Button = styled.button`
background: ${props => props.primary ? "palevioletred" : "white"};
color: ${props => props.primary ? "white" : "palevioletred"};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`
render(
<div>
<Button>Normal</Button>
<Button primary>Primary</Button>
</div>
)
继承样式
形如:
Const sub=styled(super)
const Button = styled.button`
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`
const TomatoButton = styled(Button)`
color: tomato;
border-color: tomato;
`
render(
<div>
<Button>Normal Button</Button>
<TomatoButton>Tomato Button</TomatoButton>
</div>
);
直接类比某tag
const Component = styled.div`
color: red;
`
render(
<Component
as="button"
onClick={() => alert('It works!')}
>
Hello World!
</Component>
)
样式多态
const Link = ({ className, children }) => (
<a className={className}>
{children}
</a>
)
const StyledLink = styled(Link)`
color: palevioletred;
font-weight: bold;
`
嵌套
const Thing = styled.div`
&.blue{
color: blue;
}
.red {
color: red;
}
const Thing2 = styled.div`
/* 应用于紧邻Thing组件的下一个Thing组件 */
& + & {
color: red;
}
`
render(
<React.Fragment>
<Thing2>第一个Thing组件</Thing2>
<Thing2>第二个Thing组件</Thing2>
<Thing className="blue" >Thing组件</Thing>
<Thing>
<p className="red" >p标签</p>
</Thing>
</React.Fragment>
)
🌰一个我最爱的例子
import React from 'react'
import styled from 'styled-components'
export default () => {
return (
<Root>
<div className="son1">
<div className="grandson1">
</div>
</div>
<div className="son2">
<div className="grandson2">
</div>
</div>
</Root>
)
}
const Root = styled.div`
/* 把root的样式写这 */
.son1{
/* son1样式 */
.grandson1{
/* grandson1样式 */
}
}
.son2{
/* son2样式 */
.grandson2{
/* grandson2样式 */
}
}
`
写在最后
拜托拜托!!🙏
点个赞再走吧!
点完👍快去用styled-components!
你一定会爱上的!!\
本文使用 mdnice 排版