styled components 是一个 css in js 类库,作用是可以将样式写成组件的形式,实现在 JS 上编写 CSS。样式进行组件化,避免像传统css那样的全局污染。最近在写关于 React 技术栈的记账项目也恰好用上了该库,因此做个学习记录。
安装与使用
如果使用的是 TypeScript, 那么要安装 TypeScript 支持
yarn add styled-components
yarn add --dev @types/styled-components // TS 类型声明文件
一个简单的栗子:
import styled from "styled-components";
const Wrapper = styled.section`
color: red;
`;
render(
<Wrapper>Hello World</Wrapper>
);
在 React 项目中使用 styled-components ,创建了 Wrapper 组件,内容有 html 结构 以及对应的 css 样式,达到了样式组件化,提高代码的复用率。
组件内部使用 className
- 当在项目中存在覆盖组件内部样式的需求,可以将 stylecomponents 和 className 混用
举个栗子:
import styled from "styled-components";
const Wrapper = styled.section`
color: red;
.inner{
color: blue;
}
`;
render(
<Wrapper>
Hello World // 字体为红色
<div className="inner">hi</div> // 字体为蓝色
</Wrapper>
);
Styling any component
- styled-components 不仅可以包含 html 结构 还可以给 自定义组件 设置样式
举个栗子:
const Link = ({ className, children }) => (
<a className={className}>
{children}
</a>
);
const StyledLink = styled(Link)`
color: red;
font-weight: bold;
`;
render(
<div>
<Link>Unstyled, boring Link</Link> // 字体正常
<br />
<StyledLink>Styled, exciting Link</StyledLink> // 字体变色加粗
</div>
);
基于 props 设置样式
- 可以将函数(“插值”)传递给样式组件,通过函数返回值来对样式进行设置
举个栗子:Wrapper 组件具有更改其颜色的状态。 当有 primary 属性时,可改变颜色
const Wrapper = styled.p`
color: ${props => props.primary ? "blue" : "black"};
`;
render(
<div>
<Wrapper>black</Wrapper> // 字体为黑色
<Wrapper primary>blue</Wrapper> // 字体为蓝色
</div>
);