样式组件化

    科技2026-08-21  7

    样式组件化

    我的旅途(My Journey)

    Like many, I first started styling React with inline CSS. It was an adjustment coming from stylesheets but I really liked the ability to define localized styles and leverage the power of Javascript. Of course, there were issues such as performance and lack of pseudo-selector support, but overall I was happy with it and there was no compelling reason or deficiency to search for another way to style my components.

    与许多人一样,我首先开始使用内联CSS来设计React的样式。 这是来自样式表的调整,但我真的很喜欢定义本地化样式并利用Javascript的功能。 当然,存在诸如性能和缺少伪选择器支持之类的问题,但是总的来说,我对此感到满意,也没有令人信服的理由或不足之处去寻找另一种方式来设计我的组件样式。

    When I was first introduced to Styled Components, I was a bit apprehensive of the benefits, having gotten used to inline CSS for so long. After all, React documentation (at the time), still used inline CSS for all their examples. As I prototyped the framework, I discovered a best of both worlds between inline CSS and traditional stylesheets.

    当我第一次被介绍给Styled Components时,我已经很习惯了内联CSS的好处,对此我有点担心。 毕竟,(当时)React文档仍然将内联CSS用于所有示例。 在对框架进行原型设计时,我发现了内联CSS和传统样式表之间的两全其美。

    样式化的组件 (Styled Components)

    While defined very differently, Styled Components act fundamentally like React components. They both take props as input and output HTML.

    尽管定义方式非常不同,但样式化组件从根本上就像React组件一样工作。 它们都将props作为输入和输出HTML。

    Let’s take this sample button component styled similarly to Bootstrap’s buttons with Styled Components.

    让我们以与具有样式化组件的Bootstrap按钮类似的样式来样例按钮组件。

    import styled from 'styled-components';const Button = styled.button` display: inline-block; padding: 6px 12px; font-size: 16px; font-family: Arial, sans-serif; line-height: 1.5; color: white; background-color: #6c757d; border: none; border-radius: 4px; :not(:disabled) { cursor: pointer; } :hover { background-color: #5a6268; }`;

    The styled component factory is imported and used to generate a button with styles using a template literal (`...`). This factory supports all valid HTML elements whether that be div, h1, p, etc. Similarly, the styles in the template literal accepts all valid CSS so you can go crazy with complex CSS selectors.

    导入styled组件工厂,并使用模板文字( `...` )来生成具有样式的按钮。 该工厂支持所有有效的HTML元素,无论是div , h1 , p等。类似地,模板文字中的样式接受所有有效CSS,因此您可能会为复杂的CSS选择器所困扰。

    用法 (Usage)

    Once defined, they act exactly like React components and are used in the exact same way — JSX. After all, Styled Components are simply React components with some styling.

    定义后,它们的行为就像React组件一样,并以完全相同的方式使用-JSX。 毕竟,样式化组件只是具有某种样式的React组件。

    const App = () => { return ( <Button onClick={() => alert('clicked!')} type="button"> Button </Button> );}; Styled Component Button 样式化的组件按钮

    Just like React components, Styled Components also accepts props and are defined in the same exact way. Styled Components will pass all (valid) DOM properties to the DOM.

    就像React组件一样,样式化组件也接受props并以相同的精确方式进行定义。 样式化组件会将所有(有效)DOM属性传递给DOM。

    内部构造 (Internals)

    Okay, so how does this work? What wizardly process is happening internally?

    好的,这如何工作? 内部正在发生什么向导过程?

    At render, Styled Components will generate a unique classname based on the defined styles.

    在渲染时,样式化组件将基于定义的样式生成唯一的类名。

    Styled Components will inject a style tag (<style>) into the HTML head, mapping the unique classname with defined styles.

    样式化组件会将样式标记( <style> )注入HTML头中,从而将唯一的类名映射为已定义的样式。

    Styled Components will render the element with the unique classname.

    样式化组件将使用唯一的类名渲染元素。

    These steps will result in the DOM structure looking like this for our example.

    这些步骤将导致DOM结构在本示例中看起来像这样。

    <!DOCTYPE html><html lang="en"> <head> <style data-styled="active" data-styled-version="5.2.0"> .bAeiQF { display: inline-block; padding: 6px 12px; font-size: 16px; font-family: Arial, sans-serif; line-height: 1.5; color: white; background-color: #6c757d; border: none; border-radius: 4px; } .bAeiQF:not(:disabled) { cursor: pointer; } .bAeiQF:hover { background-color: #5a6268; } </style> </head> <body> <div id="root"> <button type="button" class="sc-bdnylx bPvsWA"> Button </button> </div> </body></html>

    扩展组件 (Extending Components)

    The styled component factory can also be used to extend existing styles. It can take a Styled Component, and return a new one in a manner reminiscent of React’s higher order components.

    styled组件工厂还可以用于扩展现有样式。 它可以使用一个样式化组件,并以一种类似于React高阶组件的方式返回一个新组件。

    const PrimaryButton = styled(Button)` background-color: #007bff; :hover { background-color: #0069d9; }`;const App = () => { return ( <PrimaryButton onClick={() => alert('clicked!')} type="button"> Primary </Button> );}; Extended Style Button 扩展样式按钮

    Using styled as a function will produce a new Styled Component that has the styles from the Button component and the new styles defined in the template literal. If styles conflict, the new styles will take precedence. All props (except for those with $ prefixes; see Styling Props) will also be passed down to the underlying component.

    将styled用作函数将产生一个新的样式化组件,该组件具有Button组件的样式和模板文字中定义的新样式。 如果样式冲突,则以新样式为准。 所有道具(带有$前缀的道具除外;请参阅样式道具)也将向下传递到基础组件。

    Similarly, The styled component factory can extend React components with a small modification.

    同样, styled组件工厂可以通过少量修改来扩展React组件。

    const ButtonComponent = ({ className }) => { return ( <Button className={className} onClick={() => alert('clicked!')} type="button" > Primary </Button> );};const PrimaryButton = styled(ButtonComponent)` background-color: #007bff; :hover { background-color: #0069d9; }`;

    The one key additional addition that enables this is the className prop. The extended Styled Component will set the className and pass it to the React Component when rendered. This className will map to the defined style just like how it works with Styled Components. So, without className, the style will not get applied.

    启用此功能的一个关键附加功能是className属性。 扩展的样式化组件将设置className并在渲染时将其传递给React组件。 这个className将映射到已定义的样式,就像它与样式化组件一起工作一样。 因此,没有className ,样式将无法应用。

    可组合样式 (Composable Styles)

    Styled Components also allows us to define reusable styles that can be composed into Styled Components.

    样式化组件还使我们能够定义可重用的样式,这些样式可以组成样式化组件。

    import styled, { css } from 'styled-components';const blackFont = css` color: black;`;const WarningButton = styled(Button)` background-color: #ffc107; :hover { background-color: #e0a800; } ${blackFont}`;const App = () => { return ( <WarningButton onClick={() => alert('clicked!')} type="button"> Warning </WarningButton> );}; Composed Style Button 组合样式按钮

    Here, blackFont is a generic style. It’s defined with a template literal using the css helper. The WarningButton and any other Styled Component can include this style with the dollar sign curly braces syntax to merge the two template literals.

    在这里, blackFont是一种通用样式。 它是使用css助手使用模板文字定义的。 WarningButton和任何其他样式化组件都可以将此样式与美元符号大括号语法一起使用,以合并两个模板文字。

    造型道具 (Styling Props)

    In addition, Styled Components themselves can use props to modify styling.

    此外,样式化组件本身可以使用道具来修改样式。

    import styled, { css } from 'styled-components';const SuccessButton = styled(Button)` ${props => props.$success ? css` background-color: #28a745; :hover { background-color: #218838; } ` : ''}`;const App = () => { return ( <SuccessButton $success onClick={() => alert('clicked!')} type="button" > Success </SuccessButton> );}; Styling Props Button 造型道具按钮

    Here, the Button component is extended to take a $success prop which will conditionally set the the success styles (using a composable style) if set to true.

    在这里,将Button组件扩展为采用$success道具,如果将其设置为true,则它将有条件地设置成功样式(使用可组合样式)。

    Though styling props do not need the $ prefix, I highly recommend it. Normally, all props are passed to the underlying component (DOM element, React Component, or Styled Component). Props with names that are prefixed with $, called transient props, are only used by the defined Styled Component and are not passed down to the underlying component. This makes it crystal clear which props are for styling and which props are for the underlying component.

    尽管样式道具不需要$前缀,但我还是强烈推荐它。 通常,所有道具都会传递到基础组件(DOM元素,React Component或Styled Component)。 名称带有$前缀的道具(称为瞬态道具)仅由已定义的样式化组件使用,而不会向下传递到基础组件。 这样就可以清楚地知道哪些道具用于样式设计,哪些道具用于基础组件。

    最后的想法 (Final Thoughts)

    Styled Components provides a simple and fantastic interface for styling. It enhances the developer experience for CSS using core React principles. It integrates so well with React that I can’t help wonder why React doesn’t just natively integrate it — it’s just that good. I will never go back to my old ways of styling.

    带样式的组件为样式提供了一个简单而出色的界面。 它使用核心React原理增强了CSS开发人员的经验。 它与React集成得很好,以至于我不禁要问为什么React不只是本地集成它-就是那么好。 我将永远不会回到原来的样式。

    资源资源 (Resources)

    Official Styled Components Documentation

    官方样式化组件文档

    Github Repo for this Article

    本文的Github回购

    CodeSandbox for this Article

    本文的CodeSandbox

    翻译自: https://medium.com/javascript-in-plain-english/the-modern-way-to-style-with-styled-components-c3c51b750b5f

    样式组件化

    相关资源:jdk-8u281-windows-x64.exe
    Processed: 0.009, SQL: 9