如何在 React 中创建组件?
组件是 React 中创建用户界面 (UI) 的构建块。有两种创建组件的方法。
-
函数组件: 这是创建组件最简单的方法。这些是纯 JavaScript 函数,它们接受 props 对象作为唯一参数,并返回 React 元素以呈现输出:
function Greeting({ message }) { return <h1>{`Hello, ${message}`}</h1>; }
-
类组件: 你也可以使用 ES6 类来定义组件。上面的函数组件可以写成类组件:
class Greeting extends React.Component { render() { return <h1>{`Hello, ${this.props.message}`}</h1>; } }
何时使用类组件而不是函数组件?
在添加 Hooks(即 React 16.8 及更高版本)后,始终建议在 React 中使用函数组件而不是类组件。因为您也可以在函数组件中使用仅在类组件中可用的状态、生命周期方法和其他功能。
但是,使用 Class 组件而不是 Function 组件仍然有两个理由。
- 如果您需要某个 React 功能,但其函数组件等效项尚未出现,例如错误边界。
- 在旧版本中,如果组件需要状态或生命周期方法, 那么您需要使用类组件。
所以这个问题的总结如下:
使用函数组件:
- 如果您不需要状态或生命周期方法,并且您的组件纯粹是展示性的。
- 为了简单性、可读性和现代代码实践,特别是使用 React Hooks 来实现状态和副作用。
使用类组件:
- 如果您需要管理状态或使用生命周期方法。
- 在需要向后兼容或与旧代码集成的场景中。
注意: 您还可以使用可重复使用的反应错误边界第三方组件,而无需编写任何类。即,无需使用类组件作为错误边界。
上述库中的错误边界的使用非常简单。
**使用 react-error-boundary 时请注意: ** ErrorBoundary 是一个客户端组件。您只能向其传递可序列化的 props,或在具有指令的文件中使用它
"use client";
。
"use client";
import { ErrorBoundary } from "react-error-boundary";
<ErrorBoundary fallback={<div>Something went wrong</div>}>
<ExampleApplication />
</ErrorBoundary>;
### React 中的状态是什么?
组件的状态是一个对象,其中包含一些可能在组件生命周期内发生变化的信息。重点是,只要状态对象发生变化,组件就会重新渲染。始终建议使我们的状态尽可能简单,并尽量减少有状态组件的数量。
让我们以具有message
状态的User组件为例。这里,useState钩子已用于向 User 组件添加状态,并返回包含当前状态和更新它的函数的数组。
import { useState } from "react";
function User() {
const [message, setMessage] = useState("Welcome to React world");
return (
<div>
<h1>{message}</h1>
</div>
);
}
每当 React 调用你的组件或访问useState
钩子时,它都会为你提供该特定渲染的状态快照。
import React from "react";
class User extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Welcome to React world",
};
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
}
State 与 props 类似,但它是私有的并且完全由组件控制,也就是说,在所有者组件决定传递它之前,任何其他组件都无法访问它。
基于类的组件中访问的 Props 如下
import React from "react";
import ReactDOM from "react-dom";
class ChildComponent extends React.Component {
render() {
return (
<div>
<p>{this.props.name}</p>
<p>{this.props.age}</p>
<p>{this.props.gender}</p>
</div>
);
}
}
class ParentComponent extends React.Component {
render() {
return (
<div>
<ChildComponent name="John" age="30" gender="male" />
<ChildComponent name="Mary" age="25" gender="female" />
</div>
);
}
}