react 组件样式

by Gilad Dayagi

通过吉拉德·达亚吉

如何使用样式化组件为React组件创建视觉变体 (How to create visual variants for React components using styled-components)

Styled-components is a library for styling React components that took the React world by storm when it was introduced at the end of 2016. The library is powerful and flexible. And solves most of the problems that classic CSS has in the so-called Component Age.

Styled-components是用于对React组件进行样式设置的库,该库在2016年底推出时风靡了React世界。该库功能强大且灵活。 并解决了经典CSS在所谓的“组件时代”中存在的大多数问题 。

In this post, I’ll look into one aspect of styling components:

在这篇文章中,我将研究样式组件的一个方面:

How to implement a component that can have multiple visual variants.

如何实现可以具有多个视觉变量的组件。

And I’ll show you three different ways to achieve this using styled-components, which I call:

我将向您展示三种使用样式化组件来实现此目的的方法,我称之为:

1: The Classic Approach

1:经典方法

2: The Component Approach

2:分量法

3: The Extending Approach

3:扩展方法

I’ll assume some knowledge of React and styled-components. But in case you need a reference, both have excellent documentation. You can find React’s docs here and styled-component’s here.

我将假设一些有关React和样式化组件的知识。 但是,如果您需要参考,两者都有出色的文档。 你可以找到阵营的文档在这里和风格的分量的位置 。

You can see a live demo of each approach here.

您可以在此处观看每种方法的现场演示。

视觉变体 (Visual variants)

In React, a component translates state and props into a visual representation. This usually means into a DOM element.

在React中,组件将状态和道具转换为视觉表示。 这通常意味着进入DOM元素。

And sometimes you need a component to switch between several visual states, depending on certain conditions. Meaning you need the component to change, perhaps, color to convey different information. For example:

有时,您需要一个组件来根据特定条件在几种视觉状态之间切换。 这意味着您需要更改组件(也许是颜色)以传达不同的信息。 例如:

  • A button can be normal, primary, secondary, disabled, etc.按钮可以是普通,主要,辅助,禁用等。
  • A list item can be selected or not selected.可以选择列表项,也可以不选择。
  • A form element can be required, with error or normal.可能需要表单元素,错误或正常。

A good example of this visual variant pattern is Bootstrap’s button styles. You style the button independent of its content and choose among a host of variants. And each variant of the button serves its own semantic purpose (like success or disabled) as opposed to appearance (like blue, round, etc.).

Bootstrap的按钮样式就是一个很好的例子。 您可以对按钮进行样式设置,使其与按钮的内容无关,然后在众多变体中进行选择。 与外观(例如蓝色,圆形等)相反,按钮的每个变体都具有自己的语义目的(例如成功或禁用)。

So how do you implement visual variants with styled-components? You can do so using the Classic Approach, Component Approach, or Extending Approach.

那么如何使用样式化组件实现视觉变体? 您可以使用经典方法,组件方法或扩展方法进行操作。

1:经典方法 (1: The Classic Approach)

Styled-components fully supports CSS. Which includes the ability to apply style rules to “subclasses” of elements. That means you can create visual variants using CSS classes not so different from how it’s done with plain CSS.

样式化组件完全支持CSS。 其中包括将样式规则应用于元素的“子类”的功能。 这意味着您可以使用CSS类创建视觉变体,与普通CSS的变体没有什么不同。

To select a variant of a component you modify the className prop. You can also pass a number of classes this way and combine several variants, say, ‘primary’ and ‘large’.

要选择组件的变体,请修改className属性。 您还可以通过这种方式传递许多类,并组合多个变体,例如“主要”和“大型”。

Example

// ButtonClassic.jsximport styled from 'styled-components'
const ButtonClassic = styled.button`  background: #fff;  color: #333;  font-size: 1em;  margin: 1em;  padding: 6px 12px;  border: 1px solid #ccc;  border-radius: 4px;  cursor: pointer;
/* Style sub-classes */  &.primary {    color: #fff;    background: #337ab7;    border-color: #2e6da4;  }  &.success {    color: #fff;    background-color: #5cb85c;    border-color: #4cae4c;  }  &.link {    color: #337ab7;    background-color: transparent;    border: none;    border-radius: 0;    font-weight: 400;  }  &.large {    font-size: 1.2em;    padding: 10px 16px;    border-radius: 6px;  }  &.disabled {    color: #ddd;    background-color: #aaa;    border: 1px solid #aaa;  }`;
export default ButtonClassic

Usage

用法

// ... &lt;ButtonClassic>Default</ButtonClassic>&lt;ButtonClassic className="primary">Primary</ButtonClassic><ButtonClassic className="success">Success&lt;/ButtonClassic>&lt;ButtonClassic className="link">Link</ButtonClassic>
// With Combos&lt;ButtonClassic className="primary large">  Primary Large</ButtonClassic>
&lt;ButtonClassic className="disabled primary large">  Primary Large Disabled</ButtonClassic>

Pros

优点

  • Easy to support several variants.易于支持多种变体。
  • Easy to combine a list of variants (for example, primary + large + disabled)易于组合变体列表(例如,主+大+禁用)
  • Code is readable and compact代码清晰易读
  • Easy to port styles from plain CSS易于从普通CSS移植样式

Cons

缺点

  • Doesn’t use standard component facilities (props)不使用标准组件设施(道具)
  • When combining classes, results depend on the declaration order of the style rule. Like in classic CSS. This may lead to unexpected behavior.组合类时,结果取决于样式规则的声明顺序。 就像经典CSS一样。 这可能会导致意外的行为。

2:分量法 (2: The Component Approach)

Styled components, like their name suggest are simply normal components. Which means they can receive props. Props that can be accessed in the style declaration and used to determine values for style rules.

样式化的组件(如其名称所暗示的)只是普通组件。 这意味着他们可以接收道具。 可以在样式声明中访问的道具,用于确定样式规则的值。

I call this the Component Approach because it works like how usual React components work. Where prop values are used to calculate the visual representation of the component. In this case, the concept is limited to styling, rather than content.

我将其称为“组件方法”,因为它的工作方式与通常的React组件的工作方式相同。 其中prop值用于计算组件的视觉表示。 在这种情况下,该概念仅限于样式而不是内容。

Example

// ButtonComponent.jsx import styled from 'styled-components'
const ButtonComponent = styled.button`  background: ${props => props.primary ? '#337ab7' : '#fff'};  color: ${props => props.primary ? '#fff' : '#333'};  font-size: 1em;  margin: 1em;  padding: 6px 12px;  border: ${props => props.primary ? '1px solid #2e6da4' : '1px solid #ccc'};  border-radius: 4px;  cursor: pointer;`
export default ButtonComponent

Usage

用法

// ...&lt;ButtonComponent>Default</ButtonComponent><ButtonComponent primary={true}>Primary</ButtonComponent>

Pros

优点

  • Standard React component behavior, deriving visual representation from props标准React组件行为,从props派生视觉表示

Cons

缺点

  • If more than two states are needed, the code can become unreadable如果需要两个以上的状态,则代码可能变得不可读
  • There is some code repetition, especially if many rules differ between variants.有一些代码重复,尤其是在变体之间有很多规则不同的情况下。

3:扩展方法 (3: The Extending Approach)

Besides primitive elements, styled-components allows us to also style custom components. So you can re-style a base or default component. And override relevant style rules to create a visual variant.

除了基本元素之外,样式化组件还允许我们对自定义组件进行样式化。 因此,您可以重新设置基本或默认组件的样式。 并覆盖相关的样式规则以创建视觉变体。

Example

// ButtonExtend.jsximport styled from 'styled-components'
const ButtonExtend = styled.button`  background: #fff;  color: #333;  font-size: 1em;  margin: 1em;  padding: 6px 12px;  border: 1px solid #ccc;  border-radius: 4px;  cursor: pointer;`
export default ButtonExtend
export const ButtonExtendPrimary = styled(ButtonExtend)`  color: #fff;  background: #337ab7;  border-color: #2e6da4;`
export const ButtonExtendSuccess = styled(ButtonExtend)`  color: #fff;  background-color: #5cb85c;  border-color: #4cae4c;`
export const ButtonExtendLink = styled(ButtonExtend)`  color: #337ab7;  background-color: transparent;  border: none;  border-radius: 0;  font-weight: 400;`

Usage

用法

// ...&lt;ButtonExtend>Default</ButtonExtend><ButtonExtendPrimary>Primary<;/ButtonExtendPrimary&gt;<ButtonExtendSuccess&gt;Success</ButtonExtendSuccess><ButtonExtendLink>Link</ButtonExtendLink>

Pros

优点

  • Each variant is a separate component每个变体都是单独的组件
  • Easy to have many variants容易有多种变体
  • Code is very readable代码可读性强

Cons

缺点

  • To get a different variant, a different component needs to be rendered vs changing a property on the same component which might be more cumbersome.为了获得不同的变体,与渲染同一组件上的属性相比,需要渲染一个不同的组件,这可能会比较麻烦。
  • Can’t easily support combining multiple variants.无法轻松地支持多个变体的组合。

摘要 (Summary)

I have listed all the ways for doing visual variants that I had a chance to try, but there might be others. Which approach is best depends on your specific needs and preferences.

我已经列出了我有机会尝试过的所有视觉变化方法,但是可能还有其他方法。 哪种方法最好取决于您的特定需求和偏好。

If you missed the link above, a live demo of the code examples is available in this webpack bin.

如果您错过了上面的链接,可以在此webpack bin中获得代码示例的实时演示。

If you know of other approaches using styled-components, let me know in the comments below.

如果您知道使用样式化组件的其他方法,请在下面的评论中告诉我。

Update (Jun 9 2017)

更新(2017年6月9日)

Styled-components V2 was released a few days ago with a slightly better way to use the Extending Approach.

样式组件V2是几天前发布的 ,使用扩展方法的一种更好的方法。

There is now a specific function for this approach named extend. The function is like the original method, but under the hood creates a new stylesheet by extending the old one. And thus doesn’t generate two classes.

现在,此方法有一个特定功能,称为extend 。 该函数类似于原始方法,但是在内部通过扩展旧样式表来创建新样式表。 因此不会生成两个类。

So the original example for the Extending Approach, would look something like this:

因此,扩展方法的原始示例如下所示:

// ButtonExtendV2.jsximport styled from 'styled-components'
const ButtonExtendV2 = styled.button`  background: #fff;  color: #333;  font-size: 1em;  margin: 1em;  padding: 6px 12px;  border: 1px solid #ccc;  border-radius: 4px;  cursor: pointer;`
export default ButtonExtendV2
export const ButtonExtendV2Primary = ButtonExtendV2.extend`  color: #fff;  background: #337ab7;  border-color: #2e6da4;`
export const ButtonExtendV2Success = ButtonExtendV2.extend`  color: #fff;  background-color: #5cb85c;  border-color: #4cae4c;`// ...

翻译自: https://www.freecodecamp.org/news/visual-variants-for-react-components-with-styled-components-dfaff6a76273/

react 组件样式

react 组件样式_如何使用样式化组件为React组件创建视觉变体相关推荐

  1. java窗口样式_美化窗口样式 java窗口界面美化包

    Axure实战006:如何美化单选复选框按钮样式? 在Axure提供的组件中,复选框的样式是固定的,不能修改.如果你想美化复选框的样式,你只能自己做.有两种方法可以美化它: 1.用构件形状作画,并通过 ...

  2. 改变elementui卡片crad样式_修改ElementUI样式的几种方式

    ElementUI是一款非常强大的前端UI组件库,它默认定义了很多美观的样式,但是我们在实际开发过程中不可避免地遇到需要修改ElementUI默认样式.下面总结了几种修改默认样式的方法. 1. 新建全 ...

  3. react node服务器_适用于初学者的服务器上的React:构建通用的React和Node应用程序...

    react node服务器 In this article we are going to learn how to build a simple "Universal JavaScript ...

  4. react 生命挂钩_如何在GraphQL API中使用React挂钩来管理状态

    react 生命挂钩 In this blog post, we are going to learn - 在这篇博客中,我们将学习- What React hooks are什么是React钩子 H ...

  5. vant 下拉框样式_使用 Vue 的 Vant.js List 列表组件实现无限下拉

    拉取历史记录,并在前端做无限下拉展示,是一个非常常见的使用场景. 最近在使用的 Vant (轻量.可靠的移动端 Vue 组件库),实现起来就非常方便. 模板实现代码 v-model="loa ...

  6. word文本样式代码样式_使用文本样式表达创建真相来源

    word文本样式代码样式 As of After Effects 17.0, you can use expressions to edit text styles in After Effects. ...

  7. css鼠标悬停样式_利用Css3样式属性Cursor来更换自定义个性化鼠标指针(光标

    原文转载自「刘悦的技术博客」 ( 利用Css3样式属性Cursor来更换自定义个性化鼠标指针(光标) ) 现而今,我们纵向的回顾整个大前端的历史,不难发现,人们对前端的审美要求越来越高,越来越严苛,与 ...

  8. div方框弯曲边样式_使用弯曲样式编辑文本

    div方框弯曲边样式 Would you like a new Notepad replacement that incorporates the latest technologies while ...

  9. css复选框样式_使用CSS样式复选框

    css复选框样式 Introduction: 介绍: Sometimes we want to develop a website or web page that would contain a f ...

最新文章

  1. Linux之vim全选,全部复制,全部删除
  2. FFMPEG命令行处理视频进阶——高阶必读
  3. c语言Winmain 错误,C语言编译错误 undefined reference to `WinMain@16'
  4. ms查约束具体代码_ECCV 2020附代码论文合集(CNN,图像分割)
  5. android 上传文件到 c 服务器,android 怎么样用socket给C服务器 发送二进制数据
  6. 让Netty入门变得简单
  7. 退休后能领到4000元以上的养老保险金处于什么水平呢?
  8. 威纶通触摸屏可以解密吗_老电工选型威纶通触摸屏时的3大技巧!知道了能帮你省事不少...
  9. 华为鸿蒙名称由来英文简介,华为鸿蒙出世!中国科研人的那些神仙翻译
  10. Luogu P1197
  11. 计算机专业120分,【哈尔滨工业大学,专业课120分】跟你唠点真情实感。
  12. 如何不改一行代码,让Hippy启动速度提升50%?
  13. elasticsearch2.4.2安装(2) --插件marvel
  14. Oracle number 类型转换为 varchar2
  15. python全栈需要学习什么_python全栈是什么意思
  16. ajax重要且常用参数
  17. PayPal轮询收款的那些事儿
  18. uniapp宽屏适配
  19. 【目标检测】一些数据集处理常用代码
  20. SpringBoot整合RabbitMQ 访问保错: reply-text=NOT_ALLOWED - access to vhost '/' refused for user 'cuit'

热门文章

  1. 数据结构学习系列文章合集
  2. React for循环渲染组件
  3. iOS scrollToItemAtIndexPath 无效的解决方案
  4. self.navigationController push到指定控制器
  5. iOS 模仿支付宝支付到账推送,播报钱数
  6. 举个栗子看如何做MySQL 内核深度优化
  7. 在后台代码中引入XAML的方法
  8. Kubernetes1.5源码分析(二) apiServer之资源注册
  9. 图像处理之噪声---椒盐,白噪声,高斯噪声三种不同噪声的区别
  10. Go 语言官网全新改版