发布于 2026-01-06 2 阅读
0

轻松掌握样式组件。

轻松掌握样式组件。

对于开发者来说,项目 UI 的样式设计至关重要,尤其是在有很多选项可供选择的情况下。今天,我们将探讨样式组件,包括它的含义、选择它的原因、其他可探索的选项以及最佳实践。

大纲

  • 什么是 Styled-Component?为什么需要它?
  • 特点和优势?
  • Styled 组件中值得探索的内容
  • 结论
  • 参考

先决条件

  • 对 React JS 有基本的了解
  • CSS基础知识
  • Node 已安装在您的电脑上
  • 终端(CMD 或其他终端)

什么是 Styled Components?为什么需要它?

Styled Components 是一个用于 React 和 React Native 的 CSS-IN-JS 样式解决方案,它使用带标签的模板字面量,允许您在 JavaScript 代码中编写作用于单个组件的纯 CSS。

Styled-Components 是一个被众多公司采用的库,也是 React 生态系统中最受欢迎的库之一。

特点和优势

  • 自动关键 CSS:样式组件会自动跟踪屏幕上渲染的组件,并仅注入其样式。结合代码拆分,您将加载最少的代码,从而提高项目性能。

  • 无类名错误:它为每个样式生成唯一的类名,您再也不用担心重复或拼写错误。

  • 更轻松地删除 CSS:如果您正在开发一个使用简洁 CSS 文件的大型项目代码库,跟踪未使用的类通常会变得非常棘手。但使用 styled-components,每个样式都与特定的组件绑定。如果某个组件不再使用,可以轻松指出,然后通过删除该组件即可轻松删除未使用的类。

  • 动态样式:就像 React 一样,将 props 传递给组件,有时需要根据 props 调整样式,styled components 使这一切变得轻松简单。

  • 维护轻松便捷:使用 styled-components 可以轻松组织样式,无需在不同的文件之间切换即可找到影响组件的文件。

  • 自动添加厂商前缀:对于某些新的 CSS 功能,您可能需要为每个浏览器编写 CSS 属性,但使用 styled components,您可以按照当前标准编写 CSS,库将处理其余部分。

StyleComponents 中值得探索的内容

  1. 主题化: styled-components 提供了全面的主题化支持,使您可以为项目样式创建主题或布局结构。主题化主要包含颜色、大小、字体和其他在整个项目中使用的通用元素,以避免重复。

    要使用 styled-components 创建主题,需要导入 Theme Provider 包装器。

import { ThemeProvider } from "styled-components"
Enter fullscreen mode Exit fullscreen mode

此主题提供程序需要一个主题对象,该对象将保存我们要应用于样式化组件的 CSS 样式或值。

    const theme = {
      color: {
        primary: "#000f55",
        secondary: "#04043f",
        white: "#fff",
      },
      fontSize: {
        large: "2.5rem",
        medium: "1.5rem",
        small: ".785rem"
      }
    }

Enter fullscreen mode Exit fullscreen mode

这是一个主题值的示例,您可以根据自己的使用场景进行扩展。

假设我们有具有这些样式的组件。

    const Button = styled.button`
        padding: 4px .7rem;
        color: ${props => props.theme.color.white};
        background: ${props => props.theme.color.primary};
        font-size: ${props => props.theme.fontSize.small};
        border-radius: 8px;
    `

    const FlexWrapper = styled.div`
        display: flex;
        align-items: center;
        justify-content: center;
    ` 
Enter fullscreen mode Exit fullscreen mode

要使用它,我们需要将 ThemeProvider 包裹在所有项目中,这些项目大多是在 App.js 文件中完成的。

    <ThemeProvider theme={theme}>
        <FlexWrapper>
            <Button>Click Please</Button>
        </FlexWrapper>
    </ThemeProvider>
Enter fullscreen mode Exit fullscreen mode

从上面的代码可以看出,项目中的所有组件都使用了 ThemeProvider,它可以轻松地将样式传递给所有子组件。

2.全局样式:创建通用样式是许多开发者都希望实现的目标,尤其是在需要添加样式来覆盖现有样式时。Styled 组件让实现这一点变得更加容易。要创建全局样式,我们需要创建一个文件来存储样式。

首先,创建一个名为“globalStyles.js”的文件,并按照以下格式进行设置:

    import { createGlobalStyle } from "styled-components/macro"

    export default createGlobalStyle`
      * {
          margin: 0;
          padding: 0;
          box-sizing: border-box;
      }
    `
Enter fullscreen mode Exit fullscreen mode

从上面的代码可以看出,我们从样式组件中导入了 createGlobalStyle,用于创建全局样式。

要使用它,我们需要导入该组件并将其添加到我们的 App.js 文件中:

    import GlobalStyles from "./globalStyles"

    function App() {
        return (
            <GlobalStyles />
            <AppContent />
        )
    }
Enter fullscreen mode Exit fullscreen mode

3.样式继承:样式继承:Styled-component 允许从另一个 styled-component 继承样式,只需将其传递给 styled 函数即可。

    import styled from "styled-components"

    const Button = styled.button`
      padding: 4px 12px;
      border-radius: 4px;
      color: #fff;
      background: #000;
    `
Enter fullscreen mode Exit fullscreen mode

这是按钮组件,让我们通过继承一些样式来创建该组件的另一个变体。

    const TransparentButton = styled(Button)`
      border: 1px solid #000;
      background: none;
      color: #000;
    `
Enter fullscreen mode Exit fullscreen mode

TransparentButton 组件将继承 Button 组件的所有样式,并用自己的样式进行更新。

4.传递属性:就像普通的 React 组件接收属性来传递数据一样,样式也需要属性来使样式动态化,使用 styled-components 可以让你通过样式传递属性。

styled-components 处理样式的方式是创建一个 React 组件,该组件渲染与 styled 对象中的属性对应的 HTML 标签。

例如,我们创建了一个样式如下的按钮组件:

    const Button = styled.button`
      padding: 4px 12px;
      border-radius: 4px;
      color: #fff;
      background: #000;
    `
Enter fullscreen mode Exit fullscreen mode

为了使其具有动态效果,我们可以将背景和颜色属性设置为 props。

    const Button = styled.button`
      padding: 4px 12px;
      border-radius: 4px;
      color:${(props) => props.color ? props.color : '#fff'};
      background: ${(props) => props.bg ? props.bg : '#000'};
    `
Enter fullscreen mode Exit fullscreen mode

观察这个新的结构化组件,颜色和背景会获取一个属性值,但如果未定义该属性,则会将其设置为默认值,这是通过创建一个三元条件作为检查来实现的。

要使用该组件,其结构如下:

    <Button color="black" bg="orange">Clicked</Button>
    <Button>Click Me</Button>
Enter fullscreen mode Exit fullscreen mode

5.样式化常规组件:样式化组件的另一个神奇之处在于,只需调用 styled() 函数并将组件名称传递给它,即可将 React 组件转换为样式化组件,然后样式将放在字符串字面量中。

    function Button({props}) {
        return (
            <button className={props.className}>Click Me</button>
        )
    }
Enter fullscreen mode Exit fullscreen mode

我们想将组件转换为样式组件,我们有一个 className 属性,它已作为 props 传递给组件,为了实现这一点,我们将遵循以下步骤。

    Button = styled(Button)`
        padding: 4px 8px;
        border-radius: 4px;
        border: 1px solid #000;
    `
Enter fullscreen mode Exit fullscreen mode

这将使用字符串字面量中的样式来设置组件的样式,然后将这些样式与组件一起渲染。

6.与其他 CSS 框架一起使用: Styled components 可以与所有 CSS 框架一起使用而不会出现任何问题,这有助于您轻松自定义来自其他框架的样式而不会出现问题。

例如,让我们创建一个带有 Bootstrap 样式的输入组件:

    const Input = styled.input.attrs({
        className: "form-control"
    })`
        background: #fff
    `
Enter fullscreen mode Exit fullscreen mode

我们使用 attrs 方法添加一个值为 form-control 的类名属性。这会为组件添加 Bootstrap 样式。

这同样适用于其他 CSS 框架,例如,如果我们使用 Tailwind CSS,那么我们应该这样写:

    const TailwindInput = styled.input.attrs({
        className: "
          mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md text-sm shadow-sm placeholder-gray-400
          focus:outline-none focus:border-sky-500 focus:ring-1 focus:ring-sky-500
          disabled:bg-gray-50 disabled:text-gray-500 disabled:border-gray-200 disabled:shadow-none
          invalid:border-pink-500 invalid:text-pink-600
          focus:invalid:border-pink-500 focus:invalid:ring-pink-500
        "
    })`
        background: #fff
    `
Enter fullscreen mode Exit fullscreen mode

上面的代码和我们之前讨论的第一个代码一样,都适用于 Tailwind 框架。

7.特殊属性:使用 styled-components 可以向 HTML 标签添加属性。

例如,我们来创建一个如下所示的按钮组件:

    const Button = styled.button`
        font-size: 0.75rem;
        font-weight: 700;
        padding: 8px 1.5rem;
        border: 1px solid green;
        color: green;
    `
Enter fullscreen mode Exit fullscreen mode

假设我们要禁用它,那么我们需要引入 disabled 属性,这可以通过 styled-components 中的 attrs 方法轻松实现。

    const Button = styled.button.attrs({
      disabled: true
    })`
        font-size: 0.75rem;
        font-weight: 700;
        padding: 8px 1.5rem;
        border: 1px solid green;
        color: green;
    `
Enter fullscreen mode Exit fullscreen mode

从上面的代码可以看出,我们向样式组件引入了 attrs 方法,这可以帮助将 disabled 属性设置为 true,如果我们想根据某些条件设置 disabled 值,这可能会很有用。

8.切换组件类型: Styled Components 的动态特性在更改渲染组件类型时非常有用。例如,假设您有一个按钮组件,您可能需要将其更改为使用链接标签而不是普通的按钮标签,您可以按照以下方法操作。

    const Button = styled.button`
        padding: 2px 5px;
        color: ${props => props.theme.color};
        border-radius: 3px;
    `
Enter fullscreen mode Exit fullscreen mode

按钮组件会创建并渲染按钮元素。我们可以通过在组件被调用时传递“as”属性并指定所需的渲染类型,轻松更改渲染类型。

    <Button as="a">Go Back Home</Button>
Enter fullscreen mode Exit fullscreen mode

这将渲染并创建带有“a”标签元素的组件,并应用组件中的所有其他元素。

也可以通过使用“withComponent”方法来实现。

     const Button = styled.button`
        padding: 2px 5px;
        color: ${props => props.theme.color};
        border-radius: 3px;
    `

    const Link = Button.withComponent("a")
Enter fullscreen mode Exit fullscreen mode

链接组件会将锚标签渲染为按钮组件的副本,这样做是为了避免代码库中出现一定程度的重复,从而允许一个组件用于不同的用例。

结论

Styled Components 有很多功能,我们无法在一篇文章中全部介绍。如果您有兴趣了解更多关于 styled-components 的信息,可以查看上面的资源,这有助于更好地理解其概念。

参考?

看完以上提示后,您可能会觉得很有趣,但如果您仍然不理解 styled-components 的概念,或者您是新手,并且愿意花些时间学习它,那么我将在这里提供一些资源链接,您可以查看这些资源以获取继续学习 styled-components 所需的知识。

文章来源:https://dev.to/emmanueloluwafemi/mastering-styled-components-with-ease-1f0k