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 usual text-align property must be written as textAlign in 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 :visited go 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 using create-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 JavaScript import syntax to import a .css file to your JavaScript file. You can then use the CSS class name in JSX elements that you want to style, like this:

webpack的优点在于,由于它可以处理资产,因此您还可以使用JavaScript import语法将.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.css convention.

为了让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.css name. Webpack will take those class names and map them to a new, generated localized name.

在构建应用程序时,webpack会自动查找名称为.module.css CSS文件。 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 :global selector 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 styles
const 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 of styled.h1 followed 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。

翻译自: https://www.freecodecamp.org/news/react-styled-components-inline-styles-3-other-css-styling-approaches-with-examples/

react内联样式

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

  1. html 三种插入css样式的方式

    三种插入css样式的方式 一.外链式引入css样式 二.内嵌式使用css样式 三.行内式引入css样式 一.外链式引入css样式 在head标签中使用<link rel="styles ...

  2. 11种常用css样式学习大结局滚动条与显示隐藏

    滚动条展示 overflow-x: hidden;/*是否对内容的左/右边缘进行裁剪*/overflow-y: hidden;/*是否对内容的上/下边缘进行裁剪*/overflow:scroll;/* ...

  3. web前端入门到实战:11种常用css样式之滚动条与显示隐藏

    滚动条展示 overflow-x: hidden;/是否对内容的左/右边缘进行裁剪/overflow-y: hidden;/是否对内容的上/下边缘进行裁剪/overflow:scroll;/左右滚动/ ...

  4. 在html中样式表的三种类型,css样式有哪几种类型?

    CSS样式可以写在哪些地方呢?从CSS 样式代码插入的形式来看基本可以分为以下3种:内联式.嵌入式和外部式三种.下面本篇文章就来给大家介绍一下CSS样式的类型,希望对大家有所帮助. 内联式样式 内联式 ...

  5. html中样式表的三种形式,CSS样式表有几种存在方式

    外部样式:将网页链接到外部样式表. 内页样式:在网页上创建嵌入的样式表. 行内标签样式:应用内嵌样式到各个网页元素标签内. 每一种方法均有其优缺点: 当要在站点上所有或部份的网页上一致地应用相同样式时 ...

  6. active vue 路由样式保持_Vue 解决父组件跳转子路由后当前导航active样式消失问题...

    举个栗子,导航栏如下图,当前新闻资讯的路由是:localhost:8083/#/new,导航栏样式如图所示: 随便挑个新闻点击后会跳转到子路由:localhost:8083/#/new/newDeta ...

  7. linux系统css样式加载不出,Linux系统虚拟主机网站访问页面css样式文件加载失败或图片无法显示的分析解决...

    问题场景:客户使用Linux系统虚拟主机,网站程序上传之后访问发现页面排版有问题,css样式文件加载失败,部分图片显示不出来,以织梦CMS程序为例,如下图所所示: 问题原因: 1.Linux系统虚拟主 ...

  8. 引入css样式属于链接式的是,(5)css样式导入

    样式的组成 1.选择器:将样式与页面中的某一个或某些标签建立联系,就要使用选择器,在head标签下写一个style标签,将需控制参数的标签名写在这个style标签下,设置属性即可通过css来控制htm ...

  9. css样式 三种引入方式 选择器 常用属性:背景属性 字体属性 边框属性 内间距 外间距 盒子模型

    一.CSS简介 1.什么是css 重叠样式表 主要是负责标签的样式 美化页面 一个网页分三大部分 结构层: 主要由html负责 负责页面的结构 表现层: 主要由css负责 页面的展示样式 美化页面 行 ...

最新文章

  1. 2022-2028年中国绝热隔音材料行业投资分析及前景预测报告
  2. [转]Javascript 绝句
  3. Linux基础知识--进程管理与计划任务
  4. Vue axios 中提交表单数据(含上传文件)
  5. 页式存储管理程序模拟_ADAS/AD开发12 - 数据存储管理
  6. set 和select 的区别
  7. 现代软件工程 第十四章 【质量保障】 练习与讨论
  8. 谈了千百遍的缓存数据一致性问题
  9. Git服务器-Gogs搭建
  10. C#andSql获取当前日期格式
  11. mysql 授予用户权限_mysql授权用户权限
  12. 梅姐为什么没能拯救雅虎?
  13. 为什么计算机专硕比学硕难考,专硕一定比不上学硕?“我们专硕”,就是鄙视链最底端的一群人”...
  14. matlab波形转换,matlab波形图怎么转换为矢量图并导出?
  15. 【转载】9个offer,12家公司,35场面试,从微软到谷歌
  16. Ruby电子书教程、经典脚本合集
  17. python 飞机大战爆炸效果_Pygame飞机大战为什么飞机与敌机碰撞后不再有图片动态切换效果...
  18. 从蚂蚁的觅食过程看团队研发(转载)
  19. 用django实现一个资产管理的系统
  20. 批处理--删除当前目录及子目录中的空文件夹或文件

热门文章

  1. 破解入门(三)-----脱壳的常用方法
  2. 计算机网络在线视频加速,加速点播 迅雷XMP全面提升在线播放速度
  3. 再谈MVP,最小可用性产品
  4. Win10通过注册表添加自启项
  5. mysql主从遇故障自动切换_mysql主宕机,主从故障切换(一主多从)
  6. vue基于el-timeline组件实现动态表格时间线
  7. 西邮计算机网络实验报告,西邮计算机网络实验报告内容模板-实验二-交换机基本配置...
  8. 12款APP用户超千万,羊驼教育靠什么打造“更大的世界”?
  9. C++ 手把手教你实现可变长的数组
  10. 计算机休眠好吗,计算机休眠有什么具体的好处吗?