样式组件
我决定将我博客上的文章搬到 dev.to 上,并按照顺序,我写的第一篇文章是关于 styled-components 的,那么我们开始吧……
虽然前端开发正在体验组件的模块化优势,但有多种方法可以对它们进行样式设置,例如 CSS、SASS、CSS Modules 等。
我想向大家介绍一下我最近最喜欢的工具:styled-components,它现在在前端越来越受欢迎。
styled-components 由Max Stoiber创建,是一个允许你在 JavaScript 中编写 CSS 代码的库,这意味着你不再需要将 .css 文件导入到页面中。除了更好地组织代码之外,你还可以在同一个项目中重用创建的组件(只需调用它们),或者在另一个项目中重用(只需复制 .js 文件)。
去年我开始开发一个 ReactJS 项目,第一次接触到了 styled-components。我是通过twitch.tv上的一个直播学习课程了解到这个超棒的库的,用过之后我就再也不想回到以前的样式编写方式了。你很快就会明白为什么!
安装
要设置 styled-components,请在项目目录中运行以下命令(如果您使用 npm):
npm install --save styled-components
瞧!
以下示例创建一个简单的按钮组件,并已设置好样式:
import styled from "styled-components";
const Button = styled.button`
background-color: #3a4042;
color: #f5f5f5;
border: 1px solid #f5f5f5;
border-radius: 4px;
padding: 0.25em 1em;
margin: 1em;
font-size: 20px;
cursor: pointer;
`;
render(
<Button>
Send
</Button>
);
结果:
现在你已经了解了设置组件样式是多么容易,你必须知道你可以设置任何组件的样式!
以下示例改编自 styled-component 网站:
const h2 = ({ className, children }) => (
<a className={className}>
{children}
</a>
)
const StyledH2 = styled(h2)`
color: #db7093;
font-weight: bold;
`;
render(
<>
<h2>Unstyled, boring Title</h2>
<StyledH2>Styled, exciting Title</StyledH2>
</>
);
结果:
你还可以将标签名称传递给 styled() 工厂调用,例如“div”、“section”,而不仅仅是组件。
根据道具进行更改
您还可以根据设置的属性更改组件状态,并使该组件具有其他样式或行为。
Tag此示例展示了如何通过将组件的 prop 设置small为 true 来改变组件的大小。
const Tag = styled.h2`
font-size: 40px;
letter-spacing: 2px;
background-color: #db7093;
color: #f5f5f5;
padding: 20px 18px;
${({ small }) =>
small &&
css`
font-size: 25px;
padding: 8px 8px;
`};
`;
render(
<div>
<Tag>Normal Tag</Tag>
<Tag small>Small tag</Tag>
</div>
);
请查看以下结果:
styled-components 最让我喜欢的一点是,你可以将组件的 props 传递给已挂载的 DOM 节点。
categoryColor此示例展示了 styled-components 如何将带有边框颜色的prop 传递给Button组件,如果 prop 没有传递值,则#ffba05使用默认颜色。
const Button = styled.button`
color: #000000;
width: 100px;
margin-right: 5px;
border-radius: 4px;
border: 4px solid
${({ categoryColor }) => categoryColor || "#ffba05"};
`;
render(
<div>
<Button>yes</Button>
<Button categoryColor={"#db7093"}>no</Button>
</div>
);
请查看以下结果:
除了提升开发者的体验之外,styled-components 还提供:
- 自动关键 CSS:styled-components 会跟踪页面上渲染的组件,并自动注入它们的样式,除此之外不添加任何其他内容。结合代码拆分,这意味着用户只需加载最少的代码。
- 无需担心类名错误:styled-components 会为您的样式生成唯一的类名。您无需担心重复、重叠或拼写错误。
- 更轻松地删除 CSS:有时很难确定某个类名是否在代码库中的其他地方被使用。styled-components 让这一切变得一目了然,因为每个样式都与特定的组件绑定。如果组件未使用(工具可以检测到这一点)并被删除,则其所有样式也会随之删除。
- 简单的动态样式:根据组件的属性或全局主题调整组件的样式既简单又直观,无需手动管理数十个类。
- 维护轻松便捷:您无需在不同的文件中查找影响组件的样式,因此无论您的代码库有多大,维护都轻而易举。
- 自动添加厂商前缀:按照当前标准编写 CSS,其余的交给 styled-components 处理。
希望你和我一样喜欢 styled-components。:)
文章来源:https://dev.to/patriciadourado/styled-components-1oj8





