React Component 是 React 框架的核心概念之一,它允许开发者以模块化的方式构建用户界面。每个组件都是独立的、可复用的,并且可以接受输入数据(props)和输出结果(children)。
React Component 类型
React 提供了多种类型的组件,包括:
- 函数组件:使用 JavaScript 函数创建的组件。
- 类组件:使用 ES6 类创建的组件。
函数组件示例
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
类组件示例
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
组件状态和生命周期
React 组件可以拥有状态(state)和生命周期方法。状态是组件内部的数据,而生命周期方法是在组件创建、更新和销毁过程中执行的方法。
状态示例
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
生命周期方法
componentDidMount
: 组件挂载后执行componentDidUpdate
: 组件更新后执行componentWillUnmount
: 组件卸载前执行
学习资源
更多关于 React Component 的内容,您可以访问我们的 React 教程。
React Component