Styled-Components 简介💅...
Styled-Components 💅 是全球领先的CSS-in-JS库框架。它们易于集成到使用其他样式方法的现有应用程序中。
通过专注于单一用例,我们成功优化了开发者的体验以及最终用户的体验。
受欢迎的主要原因是:我们终于可以在样式表中使用 JavaScript 的强大功能了💪。
使用 JavaScript 修改样式最简单的方法是使用内联样式。它虽然不是非常高效,甚至不够优雅,但绝对合法,而且这种技术最大的好处是样式会被封装在组件的范围内。
React 从一开始就支持内联样式,因此它可以成为在React 应用程序中创建样式的一种方式⚛️。
注意:样式化组件适用于 React 和 React Native,虽然你一定要查看 React Native 指南,但我们在这里的重点是 React 的样式化组件。
安装⚙️
就像使用 React.js 开发所需的几乎所有其他东西一样,Styled-Components 可以通过 NPM 安装。
npm i styled-components
或者yarn add styled-components
开始🏃
然后,你可以将库导入 React.js,并创建我们的第一个样式组件。在你的 React 代码中输入以下几行:
import styled from "styled-components";
// Styled component named StyledButton
const StyledButton = styled.button`
background-color: black;
color: red;
font-size: 15px;
`;
function OurFirstComponent() {
// any other component
return <StyledButton> Login </StyledButton>;
}
vscode-styled-components是 VS Code 的一个很棒的扩展。
首先,您必须styled
从styled-components包中导入函数,然后,您可以从预定义的 HTML 标签集(该库支持所有标签)中选择一个有趣的组件来使用。
导入语句之后的代码部分看起来像函数调用,但这里我们使用反引号😮而不是括号。
styled-components 使用 JavaScript ES6 标准中的最新功能之一,称为标记模板文字。
所以基本上,反引号之间的代码就是按钮函数的主体。
是不是看起来很眼熟👀?嗯,确实很眼熟,因为这是一段使用常规 CSS 语法的常规 CSS 代码。
在原始 HTML 和 CSS 中,我们会得到这样的内容:
button {
background-color: black;
color: red;
font-size: 15px;
}
<button> Login </button>
简而言之🤏:StyledButton 是样式化的组件,它将被呈现为带有所包含样式的 HTML 按钮。styled 是一种内部实用方法,可将样式从 JavaScript 转换为实际的 CSS。
就这样!如果你懂 CSS,入门简直太容易了😃。我们继续吧👉。
传递 props
样式组件功能强大,因此您可以轻松地动态设置元素的样式。
想象一下,您的页面上有两种按钮,它们具有不同的背景颜色,而您又不允许创建两个不同的样式组件。那么您该怎么办呢?🤔
在这种情况下,我们可以根据它们的 props 调整它们的样式。我们可以像在其他 React 组件中传递属性一样,将附加属性传递给样式化的组件:
import styled from "styled-components";
const StyledButton = styled.button`
border: none;
min-width: 300px;
font-size: 15px;
padding: 6px 8px;
/* the resulting background color will be based on these props */
background-color: ${props => props.bg === "black" ? "black" : "red";
`;
function BackgroundComponent() {
return (
<div>
// Use of different props
<StyledButton bg="black"> Button1 </StyledButton>
<StyledButton bg="red"> Button2 </StyledButton>
</div>
)
}
这里,StyledButton
是一个接受 props 的 React 组件,我们可以根据 props 的存在或值来分配不同的背景颜色bg prop
。是不是很酷😎?
更多功能✍️
我提供的示例非常简单和基础,但styled-components具有更多有用的功能,包括:
-
主题- Styled-components 提供主题功能并使您能够支持多种外观和感觉。
-
嵌套规则– 如果您熟悉 SASS 或 LESS 预处理器,您就会知道嵌套规则非常有用。使用 styled-components 也可以实现嵌套规则。
-
范围选择器——您不必考虑命名约定来避免页面上的选择器冲突。
-
死代码消除——Styled-components 有一个可选配置,可以删除不影响程序结果的代码。
-
全局样式- styled-components 框架还允许您创建应用于所有 styled-components 的全局样式。
-
服务器端渲染支持——通过使用 ServerStyleSheet 对象和 StyleSheetManager,您可以利用客户端的所有样式并从服务器端返回它们。
-
Stylelint 支持– 当您必须调试样式时,良好的实时 linting 是无价的。
-
与其他 CSS 框架一起使用– 您可以将 styled-components 与任何 CSS 框架(如 Material Design 样式组件)一起使用。
如您所见,使用styled-components时可以使用许多功能。
欲了解更多信息,请查阅styled-components 文档。
在您刚开始使用 styled-components 时,它背后的想法可能会很奇怪,但如果您尝试一下,您就会爱上它😍。
感谢阅读💙!祝你拥有美好的一天 :)
在 Twitter 上关注我@Adyasha805。
这篇文章也发布在我的博客页面上。