react中样式冲突

by Vinh Le

由Vinh Le

如何通过React中的样式使您的应用漂亮 (How to make your apps pretty with styling in React)

When it comes to styling in React, there are just so many ways and choices of technologies to beautify your web app. Nonetheless, based on my personal experience, it really depends on the UI requirements of your app to decide which to go with.

当涉及到React中的样式时,有太多的方法和技术选择可以美化您的Web应用程序。 但是,根据我的个人经验,它实际上取决于应用程序的UI要求来决定要使用哪个。

太容易了吗? (Is it too easy?)

If you stop here and say: “It is easy! Just Google to find out top React UI libraries, pick one of them, and you’re good to go”, then you perhaps have not gone through painful experiences configuring pre-styled components in those libraries.

如果您在这里停下来说:“很容易! 只是Google找出了最佳的React UI库,选择其中的一个,您就很高兴了”,那么您可能还没有经历过在这些库中配置预样式化组件的痛苦经历。

The more time you work on something, the more familiar you are and the less time you need to spend troubleshooting. Styling in React is not an exception. However, it truly requires a decent amount of time, at least for me as a self-taught developer, to be able to make a wise choice.

您从事某项工作的时间越多,您就越熟悉,并且花费在故障排除上的时间也就越少。 React中的样式也不例外。 但是,这确实需要相当长的时间,至少对于我这个自学成才的开发人员而言,才能够做出明智的选择。

Therefore, my main purposes on this article is to quickly introduce best React styling alternatives and more importantly, try to further elaborate to you when you should use which.

因此,我在本文中的主要目的是快速介绍最佳的React样式替代方法,更重要的是,尝试在何时使用它们时进一步向您详细说明。

为什么要造型? (Why styling?)

Another dead simple question, isn’t it? Well, if I alter that question a tiny bit: “Why learn styling right when you start learning React?”, it might perhaps activate your thought flow.

另一个死的简单问题,不是吗? 好吧,如果我稍微改变一下这个问题:“为什么在开始学习React时为什么要正确学习样式?”,它也许会激活您的思想流程。

If you are a newcomer to React ecosystem, your very first tutorials probably teach you how to start a project, show you how to manage states and handle props. Styling is merely mentioned in the first sections of online courses and therefore minimally used in your very first apps.

如果您是React生态系统的新手,那么您的第一篇教程可能会教您如何启动项目,向您展示如何管理状态和处理道具。 样式仅在在线课程的第一部分中提到过,因此在您的第一个应用程序中很少使用。

Before I sound over-serious to you, let me tell you that “It is entirely fine.” There is absolutely nothing wrong with how you are doing. On the other hand, it is even better if you put styling aside at the beginning to focus more on logic and functionalities of the app.

在我对您听起来过分认真之前,让我告诉您“这完全没问题。” 你的表现绝对没有错。 另一方面,如果您一开始就将样式放在一旁,而将重点更多地放在应用程序的逻辑和功能上,那就更好了。

However, if you do care about the aesthetics of your work from the very beginning, then you are probably not totally satisfied with your functional but minimally styled app.

但是,如果您从一开始就关心您的作品的美观性,那么您可能对功能强大但样式简约的应用并不完全满意。

Okay, enough words. Let me summarize the benefits of styling your app, either from your very first “Hello world” or a project that you are in the middle of:

好吧,足够的话。 让我总结一下,从您的第一个“ Hello world”到您正在从事的项目中,设计应用程序样式的好处:

  • Beautiful user interface at start — remember why React exists? To help us create dynamic UI. A more polished user interface contributes to a better user experience. As a result, if we put ourselves in the users’ shoes, we simply realize that appealing design is an imperative part of a user-friendly application.

    开始时漂亮的用户界面 -还记得为什么React存在吗? 帮助我们创建动态UI。 更完善的用户界面有助于改善用户体验。 结果,如果我们将自己放在用户的鞋子上,我们就会简单地意识到吸引人的设计是用户友好应用程序的必要组成部分。

  • Good development environment — especially when you are working on your side project. If a good design makes you enjoy using it, you will perhaps have more inspiration for developing an app with a design-first approach. Again, this comes from the aesthetic sides of things. If you are the one who just want it to work, this might not be applicable for you.

    良好的开发环境 -尤其是在进行副项目时。 如果一个好的设计使您喜欢它,那么使用以设计为先的方法开发应用程序可能会获得更多启发。 同样,这来自事物的美学方面。 如果您只是想让它工作,那可能对您不适用。

  • Avoidance of styling overwhelm later on — imagine when you have worked on a project for a while and suddenly look back to think about how much you are going to need to do styling. If it is just a sandbox project, then it’s perhaps fine. But if your app requires multiple layers of containers and elements, and responsiveness is a must, then it would be quite a big amount of work ahead.

    避免样式设置过后不堪重负 -想象一下,当您在一个项目上工作了一段时间后,突然回头想一想您需要进行多少样式设置。 如果这只是一个沙盒项目,那就很好。 但是,如果您的应用程序需要多层容器和元素,并且必须具备响应能力,那么未来将需要进行大量工作。

Then what should I use to make my React app look good?

那我应该怎样使我的React应用看起来不错呢?

内联样式 (Inline styling)

This approach is the easiest way to start as it requires non-configuration and you can instantly see the result. However, even if you are familiar with CSS, be aware of typos as they might cause you headaches:

这种方法是最简单的启动方法,因为它不需要配置,您可以立即看到结果。 但是,即使您熟悉CSS,也要注意拼写错误,因为它们可能使您头痛:

<div style={{ width: 50, height: 50, background: '#000'}}>    I am a square box with black background</div>

外卖 (Takeaways)

  • Inline styling is done by the style property in any DOM element, it has an object type, in which key is a normal CSS property, and value is the equivalent CSS value.

    内联样式是由任何DOM元素中的style属性完成的,它具有对象类型,其中key是常规CSS属性,而value是等效CSS值。

  • Because there is no dash like many CSS properties, you should notice capitalization such as: backgroundColor, backgroundImage, textAlign, and flexDirection.

    因为没有像许多CSS属性那样的破折号,所以您应该注意大写,例如: backgroundColorbackgroundImagetextAlignflexDirection

  • It is more well-organized when you define a distinctive variable storing all styling logic:当您定义一个存储所有样式逻辑的独特变量时,它组织得更好:
const styles = {  alertMessage: { color: 'red' },  ... // other styling rule};...
<span style={styles.alertMessage}>Unknown error</span>
  • You can do conditional styling. For example:您可以执行条件样式。 例如:
<span    style={{ color: this.state.isWarning ? ‘red’ : ‘black’  }}>   Let’s see if I am a warning </span>. </span>

优点 (Pros)

  • Easy to apply, non-configuration.易于应用,无需配置。

缺点 (Cons)

  • Your JavaScript files will get messier and longer when your project gets more complex. One way to do it is to define style variables in an external JavaScript file and import them back. However, this does requires an extra step and becomes more difficult to use compared with following styling methods below.当您的项目变得更复杂时,您JavaScript文件将变得更加混乱和漫长。 一种方法是在外部JavaScript文件中定义样式变量,然后将其重新导入。 但是,这确实需要一个额外的步骤,并且与下面的以下样式方法相比,变得更加难以使用。
  • Lower speed of development caused by app’s reloading. If you use tools like create-react-app, your app will hot-reload every time you make changes. Otherwise, you have to manually reload your page to see changes. Therefore, depending on the complexity of your app, it will take a gradually longer amount of time just for re-rendering.应用程序的重新加载导致开发速度降低。 如果您使用诸如create-react-app之类的工具,则您的应用会在每次进行更改时热加载。 否则,您必须手动重新加载页面以查看更改。 因此,根据您应用程序的复杂性,重新渲染将花费更长的时间。

什么时候使用? (When to use?)

When you first started learning React would be the most appropriate time to pick up this approach. Besides, if your project is small or you just want to apply some minor styling on top of your app. Responsiveness, for instance, is not really critical. Then inline styling is good to go.

刚开始学习React时,是最合适的时间采用这种方法。 此外,如果您的项目很小,或者您只想在应用程序顶部应用一些较小的样式。 例如,响应能力并不是很关键。 然后可以使用内联样式。

CSS (CSS)

Okay, no more weird CSS-in-JS. Here is original CSS that you’ve loved :), only a simple configuration before you start:

好的,不再有怪异CSS-in-JS。 这是您喜欢的原始CSS :),在开始之前只有一个简单的配置:

  • Create your CSS file and import it into a JavaScript file:创建CSS文件并将其导入JavaScript文件:
import ‘./App.css’;
  • Add className to the element that you want to apply a style to:将className添加到要向其中应用样式的元素:
<p className=’warning-message’>Warning</p>

Notice that it is now className, not normal class — just a typical React thingy.

请注意,它现在是className ,而不是普通 - 只是一个典型的React whaty。

  • Followed by your styling rules:遵循您的样式规则:
App.css.warning-message { color: red;}
  • Conditional styling by setting equivalent class name:通过设置等效的类名进行条件样式设置:
<p   className={this.state.warning ? ’warning-message’ : ‘normal-message’}>Warning</p>

优点 (Pros)

  • Write CSS rules that you’re familiar with, less risk of making typos.编写您熟悉CSS规则,减少输入错误的风险。
  • Benefits from CSS features such as variables and media queries.受益于CSS功能,例如变量和媒体查询。
  • Well-organized project structure.组织良好的项目结构。
  • Higher development speed — this is perhaps the most enjoyable upside that I’ve experienced in development. When you make changes in your CSS files, your app will not be re-rendered. Therefore, it will take a second for your updates to display on the screen. The bigger and more complex your app is, the more pleasure you will feel saving those unnecessary reloading time.

    更高的开发速度 -这也许是我在开发中所经历过的最愉快的时光。 在CSS文件中进行更改时,不会重新呈现您的应用程序。 因此,您的更新将需要一秒钟才能显示在屏幕上。 您的应用程序越大,越复杂,就可以节省更多不必要的重新加载时间,从而获得更多的乐趣。

缺点 (Cons)

  • Missing features compared to SCSS, which I will dive into right after this.与SCSS相比缺少的功能,在此之后我将深入探讨。

什么时候使用? (When to use?)

You can use CSS from the beginning, regardless of your app’s size. As it is almost zero-configuration and CSS is perhaps familiar with many, it is easy to quickly start.

无论您的应用大小如何,都可以从一开始就使用CSS。 由于几乎是零配置,并且CSS可能很熟悉,所以很容易快速启动。

If your app is getting bigger and having an even more complex design system, consider checking benefits of SCSS over CSS.

如果您的应用程序越来越大且具有更复杂的设计系统,请考虑检查SCSS与CSS相比的优势。

Nonetheless, keep in mind that you’ll be totally fine with pure CSS. SCSS is not really a game-changer that offers you all benefits that you would not get out of CSS. Recently, brand new features like variables are coming to minimize the gap between CSS and its preprocessors. Besides, if you have not used SCSS before, it will does take some times to familiarize with it.

尽管如此,请记住,使用纯CSS将会完全没问题。 SCSS并不能真正改变游戏规则,它可以为您提供CSS不能带来的所有好处。 最近,诸如变量之类的崭新功能将使CSS及其预处理器之间的差距最小化。 此外,如果您以前没有使用过SCSS,则需要花费一些时间来熟悉它。

SCSS (SCSS)

This is perhaps my go-to choice for React styling. It takes all familiarity and benefits of CSS plus a number of very useful features to make a great package. If you are not familiar with SCSS, they have awesome docs for you to check out.

这也许是我对React样式的首选。 它需要CSS的所有熟悉度和好处,以及许多非常有用的功能,才能构成一个很好的程序包。 如果您不熟悉SCSS,他们会提供很棒的文档供您检查。

In order to make use of SCSS in your React app, it does require a few configurations, though. If you are using create-react-app, this guideline might be helpful for you.

为了在您的React应用程序中使用SCSS,它确实需要一些配置。 如果您使用的是create-react-app,则该指南可能会对您有所帮助。

Next, let me show you the benefits of SCSS that makes it a superior choice compared with normal CSS.

接下来,让我向您展示SCSS的优点,它使它比普通CSS优越。

套料 (Nesting)

When your project gets bigger, the chance is highly likely that your CSS files are going to be full of class names. Things get even more daunting when your design consists of nested blocks, containers and elements. Finding a particular class name somewhere in a hundreds-line file is thus tiring and time-consuming. Here is where nesting comes in handy:

当您的项目变大时,您CSS文件很有可能充满类名。 当您的设计由嵌套的块,容器和元素组成时,事情变得更加艰巨。 因此,在数百行文件中的某个位置查找特定的类名称会很累并且很费时间。 这是嵌套派上用场的地方:

App.scss.intro-container {  h1 { font-size: 20px };  .nested-child {    display: block;    p {      margin: 0;    }  }}

With this structure, for instance, you want to change style of a child element inside your intro container. All you need to do right now is to find its class name, which is intro-container in this case. Then all styles of its children could be found inside it. Much easier, isn’t it?

例如,通过这种结构,您想要更改intro容器内的子元素的样式。 您现在需要做的就是找到它的类名,在这种情况下,该类名是intro-container 。 然后可以在其中找到所有样式的子项。 容易得多,不是吗?

混合蛋白 (Mixins)

One of the greatest benefits that mixins bring to the table is to define breakpoints in media queries. Let’s take a look at this example:

mixins带给表的最大好处之一就是定义媒体查询中的断点。 让我们看一下这个例子:

_mixins.scss
// define breakpoint for mobile device  @mixin bp-mobile {    @media only screen and (min-device-width: 320px) and (max-device-width: 480px) {      @content;    }  }

Back in the main SCSS file:

返回主SCSS文件:

App.scss
body {  width: 60%; margin: 0 auto;  @include bp-mobile {    width: 90%;  }}

Compared to:

相比:

App.css
// set width of the body to 90% only in mobile devicesbody {  width: 60%; margin: 0 auto;}...@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {  body {    @include bp-mobile {      width: 90%;    }  }}

I believe that it is much more natural and easier in SCSS. As when you apply styling rules for one element, you have a clear view of how it looks in other viewports. Therefore, changes and adjustments are made directly without the burden of scrolling up in CSS as people normally define media queries at the end of CSS file.

我相信这在SCSS中更加自然和容易。 当您对一个元素应用样式规则时,就可以清楚地看到其在其他视口中的外观。 因此,由于人们通常在CSS文件末尾定义媒体查询,因此可以直接进行更改和调整,而无需在CSS中向上滚动。

遗产 (Inheritance)

This is extremely helpful in making your code DRY. Let’s say if you want to apply similar background and border for 2 buttons, except one of them has red text color and the other has blue one:

这对于使代码DRY极为有用。 假设您要为2个按钮应用相似的背景和边框,除了其中一个具有红色文本颜色,另一个具有蓝色文本颜色:

// define common rules%button-common {  background: #fff;  border: 1px solid gray;  border-radius: 3px;}
.button-red {  @extend %button-common; color: ‘red’;}
.button-blue {  @extend %button-common; color: ‘blue’;}

Let’s summarize pros and cons of SCSS:

让我们总结一下SCSS的优缺点:

优点 (Pros)

  • Basically all pros from CSS plus distinctive features that make people love SCSS.基本上,所有来自CSS的专家以及使人们喜欢SCSS的独特功能。

缺点 (Cons)

  • Requires configuration to use.需要配置才能使用。
  • Does take a certain amount of time to learn for folks who are not familiar with SCSS.对于不熟悉SCSS的人来说,确实需要花费一些时间来学习。

React UI库 (React UI Libraries)

Thanks to the thriving of the open-source community, there are awesome React UI libraries that you can take into use in your projects. Excellent resources are MaterialUI, React-Bootstrap… to name but a few.

感谢开源社区的兴旺发展,您可以在项目中使用很棒的React UI库。 优秀的资源是MaterialUI , React-Bootstrap …等等。

Let’s take MaterialUI, one of the most popular libraries, as a demo:

让我们以最受欢迎的库之一MaterialUI为例进行演示:

安装 (Installation)

npm install @material-ui/core

In order to use this, you have to rely heavily on its documentation, which is drafted nicely and designed in, well, the Google material way. However, if you look at a code sample for its components, it is kind of daunting. My way is to just import the component that you want to use, notice some important props, and customize it later.

为了使用它,您必须严重依赖于它的文档,该文档起草得很好,并且以Google的实质性方式设计。 但是,如果您查看其组件的代码示例,这会令人望而生畏。 我的方法是只导入要使用的组件,注意一些重要的道具,并在以后对其进行自定义。

Let’s say if we want to create a button:

假设我们要创建一个按钮:

App.js
import { Button } from ‘@material-ui/core’;...
<Button  color=’primary’  onClick={() => console.log(‘clicked’)}  fullWidth> View </Button>

Boom! A button with label “View”, blue color, having a width value equal to the one of its parent container, appears nicely on the screen.

繁荣! 屏幕上会很好地显示一个带有标签“ View”(蓝色)的按钮,其宽度值等于其父容器的宽度。

Just like this, you can pretty much get use of all components in the library. The advantage of using it is an apparently polished and modern material design. If you want to create a component on your own, it will perhaps take a good amount of work and your final result might not even look as good as pre-styled components.

就像这样,您几乎可以使用库中的所有组件。 使用它的优点是表面经过抛光和现代的材料设计。 如果您想自己创建一个组件,则可能需要花费大量的工作,并且最终结果可能甚至不如预样式化的组件。

那么,为什么我们不都使用它呢? (So why don’t we just all use this?)

First of all, if making it appear on the screen seems to be super easy, customizing and making it perfectly fit into your design system is absolutely not an easy task.

首先,如果使它出现在屏幕上似乎超级简单,那么自定义并使之完全适合您的设计系统绝对不是一件容易的事。

One way to customize those components is to override its style, most of the time through style prop. Another way is to give it a class name, and write its own style by CSS. In this case, if your CSS is totally valid but your component does not change at all, remember to put !important after your rules.

定制这些组件的一种方法是在大多数情况下通过样式道具覆盖其样式。 另一种方法是给它一个类名,并通过CSS编写自己的样式。 在这种情况下,如果您CSS完全有效,但是您的组件完全没有变化,请记住在规则后面加上!important

那么什么时候使用React UI库呢? (So when would you use React UI libraries?)

If you are working on a side project which is small, libraries like MaterialUI are nice to use. As you’ll only have to focus on the JavaScript side of things and still have a pretty nice-looking app.

如果您正在做一个很小的副项目,那么像MaterialUI这样的库就很好用了。 因为您只需要专注于JavaScript方面,仍然拥有一个外观漂亮的应用程序。

However, when you plan to make a complex app with nested layers of UI, do notice that sometimes it might be even faster to create your own reusable components than try to customize pre-styled ones. In my personal experience, if you really need particular components where they are so difficult to style or make them behave like what you wish, then you take them into use. Otherwise, it is better to create your own and take full advantage of your control over them.

但是,当您计划使用嵌套的UI层制作复杂的应用程序时,请注意,有时创建自己的可重用组件比尝试自定义预先样式化的组件更快。 以我个人的经验,如果您确实需要特殊的组件,而这些组件很难样式化或使其表现出所需的效果,则可以使用它们。 否则,最好创建自己的并充分利用对它们的控制权。

So, here they are, popular ways to style in React. Of course, there are still many other great libraries and hacks out there. Please share yours down bellow in the comment section. As the React community is growing bigger and bigger, we can expect an even increasing number of “rising stars”.

因此,这里是在React中进行样式设置的流行方法。 当然,还有许多其他很棒的库和技巧。 请在评论部分中分享您的意见。 随着React社区变得越来越大,我们可以期待越来越多的“后起之秀”。

Furthermore, awesome maintainers and developers of current open-source libraries will only try to make their solutions better, more polished, and easier to use. Those all signify a bright future ahead :)

此外,当前开放源代码库的优秀维护者和开发人员将仅尝试使他们的解决方案更好,更精巧并且更易于使用。 这些都预示着光明的未来:)

谢谢阅读! (Thanks for reading!)

在社交媒体上问好: Facebook , Twitter , LinkedIn或我的个人网站 。 (Say hello on Social Media: Facebook, Twitter, LinkedIn, or my personal site.)

请继续关注即将到来的技术博客? ? ? (Stay tuned for upcoming tech blogs ? ? ?)

再见! (See you soon!)

翻译自: https://www.freecodecamp.org/news/styling-in-react-101-2536b696219b/

react中样式冲突

react中样式冲突_如何通过React中的样式使您的应用漂亮相关推荐

  1. react 组件中使用组件_禁止使用React功能组件的7个理由

    react 组件中使用组件 Are React's Functional Components Worth The Cost? React的功能组件值得吗? Update 5/31/19: React ...

  2. react 组件引用组件_自定位React组件

    react 组件引用组件 While React has ways to break the hatch and directly manipulate the DOM there are very ...

  3. react 日期怎么格式化_手写React的Fiber架构,深入理解其原理

    熟悉React的朋友都知道,React支持jsx语法,我们可以直接将HTML代码写到JS中间,然后渲染到页面上,我们写的HTML如果有更新的话,React还有虚拟DOM的对比,只更新变化的部分,而不重 ...

  4. jsonp react 获取返回值_谈谈对 React 新旧生命周期的理解

    前言 在写这篇文章的时候,React 已经出了 17.0.1 版本了,虽说还来讨论目前 React 新旧生命周期有点晚了,React 两个新生命周期虽然出了很久,但实际开发我却没有用过,因为 Reac ...

  5. python在word中的应用_不能在worddoc中使用docx python应用表样式

    我不能使用python3.4将自定义表样式应用于worddoc.我遵循了@scanny的一个很好的方法:我创建了一个空白WORD doc,创建了一个自定义表样式,并将其保存为"OR" ...

  6. 地图样式自定义_干货在线 | ArcGIS中定义图框样式

    ArcGIS系统中的样式可能不能满足实际生产需要,为了实现快速制图,可自定义一些样式,以便重复利用. 安装字符 因为样式中定义了自定义的符号,这些符号都打包到字体中,所以在使用样式之前,必须安装字体文 ...

  7. idea ubuntu 与 快捷键冲突_解除Intellij Idea中的热键冲突

    在Intellij Idea中常用的热键包括有Ctrl+Alt+s,Ctrl+Alt+L,Ctrl+Alt+Left,Alt+F7,而这些热键已经在Gnome中注册,这就导致了热键冲突. 执行以下脚本 ...

  8. 范数在机器学习中的作用_设计在机器学习中的作用

    范数在机器学习中的作用 Today, machine learning (ML) is a component of practically all new software products. Fo ...

  9. 符号在excel中的引用_如何在Excel中添加项目符号

    &符号在excel中的引用 There's no built-in feature for bullets in Excel, like there is in a Word document ...

最新文章

  1. des算法java_Java加密算法笔记--DES算法实现
  2. ML之回归预测:利用13种机器学习算法对Boston(波士顿房价)数据集【13+1,506】进行回归预测(房价预测)+预测新数据得分
  3. Syntax error, parameterized types are only available if source level is 1.5
  4. mac os 开启redis_【漫画】谈谈Redis持久化
  5. .NET : 自定义TraceListener
  6. ARCore之路-环境配置
  7. WinCC V7.4 过程值归档概述及流程演示
  8. 语音信号处理、语音特征提取
  9. Windows 如何完整备份驱动
  10. 图(3)——邻接链表法
  11. 安装及配置 Mac 上的 Rime 输入法——鼠鬚管 (Squirrel)(也适用于小狼豪)
  12. AI-多模态-2021:ALBEF
  13. 巴蜀3540 -- 【Violet 6 最终话】蒲公英
  14. BUUCTF Reverse前五题解题记录
  15. 海量过程数据的 CPK 与 PPK 计算
  16. 高曼数位板触控笔无反应问题
  17. linux xrdp 远程桌面,详解如何在Ubuntu 20.04上安装Xrdp服务器(远程桌面)
  18. 1656_MIT 6.828 JOS i386_init的实现分析
  19. Matlab:元胞(cell)
  20. Halcon、opencv与C++的图像数据转换

热门文章

  1. Java面试题及答案,java底层实现原理
  2. 我想谈谈关于Android面试那些事,一篇文章帮你解答
  3. java 生成二维码
  4. 代码整洁之道,clean code
  5. [leetcode] N-Queens II
  6. Linux 环境下搭建 Jenkins(Hudson)平台
  7. 3.9 对称三位素数
  8. Nancy简单实战之NancyMusicStore(四):实现购物车
  9. apache配置解析php
  10. linux文件分割(将大的日志文件分割成小的)