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

本文介绍了四种为React应用样式化的技术:内联样式、CSS样式表、CSS模块和样式化组件。内联样式允许直接在组件中以对象形式设置样式,但不支持伪类和媒体查询。CSS样式表通过导入CSS文件提供更丰富的功能,但可能导致全局样式冲突。CSS模块通过局部化类名解决了冲突问题,允许继承和代码复用。最后,样式化组件结合了CSS in JS和CSS模块的优点,提供自动关键CSS、独特的类名和动态样式等特性。
摘要由CSDN通过智能技术生成

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";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值