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";