300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > react内联样式_React样式化的组件:内联样式+ 3种其他CSS样式化方法(带有示例)...

react内联样式_React样式化的组件:内联样式+ 3种其他CSS样式化方法(带有示例)...

时间:2023-02-06 18:46:24

相关推荐

react内联样式_React样式化的组件:内联样式+ 3种其他CSS样式化方法(带有示例)...

react内联样式

There's no one right way to style your React components. It all depends on how complex your front-end application is, and which approach you're the most comfortable with.

没有一种正确的方式来设计您的React组件。 这完全取决于您的前端应用程序的复杂程度,以及您最适应哪种方法。

There are four different ways to style React application, and in this post you will learn about them all. Let’s start with inline styling.

有四种不同的方式来对React应用程序进行样式设置,在本文中,您将了解所有这些方法。 让我们从内联样式开始。

内联样式 (Inline Styling)

React components are composed of JSX elements. But just because you’re not writing regular HTML elements doesn’t mean you can’t use the old inline style method.

React组件由JSX元素组成。 但是,仅仅因为您没有编写常规HTML元素并不意味着您不能使用旧的内联样式方法。

The only difference with JSX is that inline styles must be written as an object instead of a string.

与JSX的唯一区别是,内联样式必须作为对象而不是字符串编写。

Here is a simple example:

这是一个简单的示例:

import React from "react";export default function App() {return (<h1 style={{ color: "red" }}>Hello World</h1>);}

In the style attribute above, the first set of curly brackets will tell your JSX parser that the content between the brackets is JavaScript (and not a string). The second set of curly bracket will initialize a JavaScript object.

在上面的style属性中,第一组花括号将告诉您的JSX解析器,括号之间的内容是JavaScript(而不是字符串)。 第二组花括号将初始化一个JavaScript对象。

Style property names that have more than one word are written in camelCase instead of using the traditional hyphenated style. For example, the usualtext-alignproperty must be written astextAlignin JSX:

具有多个单词的样式属性名称是使用camelCase编写的,而不是使用传统的连字符样式。 例如,通常的text-align属性必须在JSX中写为textAlign

import React from "react";export default function App() {return (<h1 style={{ textAlign: "center" }}>Hello World</h1>);}

Because the style attribute is an object, you can also separate the style by writing it as a constant. This way, you can reuse it on other elements as needed:

因为style属性是一个对象,所以您还可以通过将其编写为常量来分隔样式。 这样,您可以根据需要在其他元素上重用它:

import React from "react";const pStyle = {fontSize: '16px',color: 'blue'}export default function App() {return (<p style={pStyle}>The weather is sunny with a small chance of rain today.</p>);}

If you need to extend your paragraph style further down the line, you can use the object spread operator. This will let you add inline styles to your already-declared style object:

如果需要将段落样式进一步扩展,可以使用对象传播运算符。 这将使您可以将内联样式添加到已经声明的样式对象中:

import React from "react";const pStyle = {fontSize: "16px",color: "blue"};export default function App() {return (<><p style={pStyle}>The weather is sunny with a small chance of rain today.</p><p style={{ ...pStyle, color: "green", textAlign: "right" }}>When you go to work, don't forget to bring your umbrella with you!</p></>);}

Inline styles are the most basic example of a CSS in JS styling technique.

内联样式是JS样式技术中CSS的最基本示例。

One of the benefits in using the inline style approach is that you will have a simple component-focused styling technique. By using an object for styling, you can extend your style by spreading the object. Then you can add more style properties to it if you want.

使用内联样式方法的好处之一是,您将拥有一种简单的以组件为中心的样式技术。 通过使用对象进行样式设置,可以通过扩展对象来扩展样式。 然后,您可以根据需要向其中添加更多样式属性。

But in a big and complex project where you have a hundreds of React components to manage, this might not be the best choice for you.

但是在一个庞大而复杂的项目中,您需要管理数百个React组件,这可能不是您的最佳选择。

You can’t specify pseudo-classes using inline styles. That means:hover,:focus,:active, or:visitedgo out the window rather than the component.

您不能使用内联样式指定伪类。 这意味着:hover:focus:active:visited离开窗口而不是组件。

Also, you can’t specify media queries for responsive styling. Let’s consider another way to style your React app.

另外,您不能为响应式样式指定媒体查询。 让我们考虑另一种样式化您的React应用程序的方式。

CSS样式表 (CSS Stylesheets)

When you build a React application usingcreate-react-app, you will automatically use webpack to handle asset importing and processing.

使用create-react-app构建React应用create-react-app,将自动使用webpack来处理资产导入和处理。

The great thing about webpack is that, since it handles your assets, you can also use the JavaScriptimportsyntax to import a.cssfile to your JavaScript file. You can then use the CSS class name in JSX elements that you want to style, like this:

webpack的优点在于,由于它可以处理资产,因此您还可以使用JavaScriptimport语法将.css文件导入到JavaScript文件中。 然后,您可以在要设置样式的JSX元素中使用CSS类名称,如下所示:

.paragraph-text {font-size: 16px;color: 'blue';}

import React, { Component } from 'react';import './style.css';export default function App() {return (<><p className="paragraph-text">The weather is sunny with a small chance of rain today.</p></>);}

This way, the CSS will be separated from your JavaScript files, and you can just write CSS syntax just as usual.

这样,CSS将从JavaScript文件中分离出来,您可以照常编写CSS语法。

You can even include a CSS framework such as Bootstrap in your React app using this approach. All you need to is import the CSS file into your root component.

您甚至可以使用这种方法在您的React应用程序中包括CSS框架,例如Bootstrap 。 您只需要将CSS文件导入到根组件中即可。

This method will enable you to use all of the CSS features, including pseudo-classes and media queries. But the drawback of using a stylesheet is that your style won’t be localized to your component.

使用此方法,您可以使用所有CSS功能,包括伪类和媒体查询。 但是使用样式表的缺点是您的样式不会本地化到您的组件。

All CSS selectors have the same global scope. This means one selector can have unwanted side effects, and break other visual elements of your app.

所有CSS选择器都具有相同的全局范围。 这意味着一个选择器可能会产生有害的副作用,并破坏应用程序的其他视觉元素。

Just like inline styles, using stylesheets still leaves you with the problem of maintaining and updating CSS in a big project.

就像内联样式一样,使用样式表仍然会给您带来在大型项目中维护和更新CSS的问题。

CSS模块 (CSS Modules)

A CSS module is a regular CSS file with all of its class and animation names scoped locally by default.

CSS模块是一个常规CSS文件,其所有类和动画名称默认情况下都在本地范围内。

Each React component will have its own CSS file, and you need to import the required CSS files into your component.

每个React组件都有其自己CSS文件,您需要将所需CSS文件导入到您的组件中。

In order to let React know you’re using CSS modules, name your CSS file using the[name].module.cssconvention.

为了让React知道您正在使用CSS模块,请使用[name].module.css约定来命名CSS文件。

Here is an example:

这是一个例子:

.BlueParagraph {color: blue;text-align: left;}.GreenParagraph {color: green;text-align: right;}

import React from "react";import styles from "./App.module.css";export default function App() {return (<><p className={styles.BlueParagraph}>The weather is sunny with a small chance of rain today.</p><p className={styles.GreenParagraph}>When you go to work, don't forget to bring your umbrella with you!</p></>);}

When you build your app, webpack will automatically look for CSS files that have the.module.cssname. Webpack will take those class names and map them to a new, generated localized name.

在构建应用程序时,webpack会自动查找名称为.module.cssCSS文件。 Webpack将采用这些类名并将其映射到新的,生成的本地化名称。

Here is the sandbox for the above example. If you inspect the blue paragraph, you’ll see that the element class is transformed into_src_App_module__BlueParagraph.

这是上面示例的沙箱。 如果检查蓝色段落,您会发现元素类已转换为_src_App_module__BlueParagraph

CSS Modules ensures that your CSS syntax is scoped locally.

CSS模块可确保CSS语法在本地范围内。

Another advantage of using CSS Modules is that you can compose a new class by inheriting from other classes that you’ve written. This way, you’ll be able to reuse CSS code that you’ve written previously, like this:

使用CSS模块的另一个优点是,您可以通过继承编写的其他类来组成一个新类。 这样,您将能够重复使用先前编写CSS代码,如下所示:

.MediumParagraph {font-size: 20px;}.BlueParagraph {composes: MediumParagraph;color: blue;text-align: left;}.GreenParagraph {composes: MediumParagraph;color: green;text-align: right;}

Finally, in order to write normal style with a global scope, you can use the:globalselector in front of your class name:

最后,为了编写具有全局作用域的普通样式,可以在类名前面使用:global选择器:

:global .HeaderParagraph {font-size: 30px;text-transform: uppercase;}

You can then reference the global scoped style like a normal class in your JS file:

然后,您可以像在JS文件中的普通类一样引用全局范围样式:

<p className="HeaderParagraph">Weather Forecast</p>

样式化的组件 (Styled Components)

Styled Components is a library designed for React and React Native. It combines both the CSS in JS and the CSS Modules methods for styling your components.

样式化组件是为React和React Native设计的库。 它结合了JS中CSS和CSS模块方法来设计组件样式。

Let me show you an example:

让我给你看一个例子:

import React from "react";import styled from "styled-components";// Create a Title component that'll render an <h1> tag with some stylesconst Title = styled.h1`font-size: 1.5em;text-align: center;color: palevioletred;`;export default function App() {return <Title>Hello World!</Title>;}

When you write your style, you’re actually creating a React component with your style attached to it. The funny looking syntax ofstyled.h1followed by backtick is made possible by utilizing JavaScript’s tagged template literals.

编写样式时,实际上是在创建一个带有样式的React组件。 通过使用JavaScript的标记模板文字,可以使styled.h1有趣的语法styled.h1后引号成为可能。

Styled Components were created to tackle the following problems:

创建样式化组件以解决以下问题:

Automatic critical CSS: Styled-components keep track of which components are rendered on a page, and injects their styles and nothing else automatically. Combined with code splitting, this means your users load the least amount of code necessary.

自动关键CSS:样式化组件可跟踪在页面上呈现哪些组件,并自动注入其样式,而不会自动注入其他内容。 结合代码拆分,这意味着您的用户可以加载最少数量的必需代码。

No class name bugs: Styled-components generate unique class names for your styles. You never have to worry about duplication, overlap, or misspellings.

没有类名错误:样式化组件会为您的样式生成唯一的类名。 您不必担心重复,重叠或拼写错误。

Easier deletion of CSS: It can be hard to know whether a class name is already used somewhere in your codebase. Styled-components makes it obvious, as every bit of styling is tied to a specific component. If the component is unused (which tooling can detect) and gets deleted, all of its styles get deleted with it.

轻松删除CSS:很难知道您的代码库中是否已经使用了类名。 样式化的组件很明显,因为样式的每一点都与特定的组件相关联。 如果组件未使用(工具可以检测到)并被删除,则其所有样式都会随之删除。

Simple dynamic styling: Adapting the styling of a component based on its props or a global theme is simple and intuitive, without you having to manually manage dozens of classes.

简单的动态样式:基于组件的属性或全局主题调整样式非常简单直观,而无需手动管理数十个类。

Painless maintenance: You never have to hunt across different files to find the styling affecting your component, so maintenance is a piece of cake no matter how big your codebase is.

无痛的维护:您不必寻找不同的文件来查找影响您组件的样式,因此无论您的代码库有多大,维护都是小菜一碟。

Automatic vendor prefixing: Write your CSS to the current standard and let styled-components handle the rest.

供应商自动前缀:将CSS写入当前标准,然后让样式化的组件处理其余部分。

You get all of these benefits while still writing the same CSS you know and love – just bound to individual components.

您将获得所有这些好处,同时仍然可以编写自己熟悉和喜爱CSS –仅限于单个组件。

If you’d like to learn more about styled components, you can visit the documentation and see more examples.

如果您想了解有关样式化组件的更多信息,可以访问文档并查看更多示例。

结论 (Conclusion)

Many developers still debate the best way to style a React application. There are both benefits and drawbacks in writing CSS in a non-traditional way.

许多开发人员仍在争论最好的方式来设计React应用程序。 以非传统方式编写CSS既有优点也有缺点。

For a long time, separating your CSS file and HTML file was regarded as the best practice, even though it caused a lot of problems.

长期以来,分离CSS文件和HTML文件被视为最佳做法,即使这样做会引起很多问题。

But today, you have the choice of writing component-focused CSS. This way, your styling will take advantage of React’s modularity and reusability. You are now able to write more enduring and scalable CSS.

但是今天,您可以选择编写以组件为中心CSS。 这样,您的样式将利用React的模块化和可重用性。 现在,您可以编写更持久且可扩展CSS。

翻译自: /news/react-styled-components-inline-styles-3-other-css-styling-approaches-with-examples/

react内联样式

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。