Styled-Components它是通过JavaScript改变CSS编写方式的解决方案之一,从根本上解决常规CSS编写的一些弊端。
通过JavaScript来为CSS赋能,我们能达到常规CSS所不好处理的逻辑复杂、函数方法、复用、避免干扰。
尽管像SASS、LESS这种预处理语言添加了很多用用的特性,但是他们依旧没有对改变CSS的混乱有太大的帮助。因此组织工作交给了像 BEM这样的方法,虽然比较有用,但是它完全是自选方案,不能被强制应用在语言或者工具层面。
他搭配React可能将模块化走向一个更高的高度,样式书写将直接依附在JSX上面,HTML、CSS、JS三者再次内聚。
安装
npm install --save styled-components
除了npm安装使用模块化加载包之外,也支持UMD
格式直接加载脚本文件
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
入门
styled-components
使用标签模板来对组件进行样式化。
它移除了组件和样式之间的映射。这意味着,当你定义你的样式时,你实际上创造了一个正常的React组件,你的样式也附在它上面。
这个例子创建了两个简单的组件,一个容器和一个标题,并附加了一些样式。
// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
// Use Title and Wrapper like any other React component – except they're styled!
render(
<Wrapper>
<Title>
Hello World, this is my first styled component!
</Title>
</Wrapper>
);
注意: CSS规则会自动添加浏览器厂商前缀,我们不必考虑它。
const Wrapper = styled.section`
width: 100%;
height: 1rem;
background: #ccc;
`
let Test0 = ({className, children})=> (
<div className={className}>222</div>
)
const Test1 = styled(Test0)`
color: red;
font-size: 0.3rem;
width: 80%;
border: 1px solid red;
box-sizing: border-box;
animation: ${run} 1s;
&.div1{
background: blue;
}
`
render(
<Wrapper>
<Title></Title>
</Wrapper>
);
对应编译成的html
在极少特殊情况下,我们可能需要更改样式组件的标签类型。我们有一个特别的API,withComponent
可以扩展样式和替换标签:
const Button = styled.button`
display: inline-block;
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
// We're replacing the <button> tag with an <a> tag, but reuse all the same styles
const Link = Button.withComponent('a')
// Use .withComponent together with .extend to both change the tag and use additional styles
const TomatoLink = Link.extend`
color: tomato;
border-color: tomato;
`;
render(
<div>
<Button>Normal Button</Button>
<Link>Normal Link</Link>
<TomatoLink>Tomato Link</TomatoLink>
</div>
);