在 React 中,组件是构建 UI 界面的基本单元。React 组件可以分为类组件和函数组件两种。
类组件是 ES6 的一个类,它继承自 React.Component,并实现了 render() 方法来返回组件的 UI。类组件可以有自己的状态(state)和生命周期方法(lifecycle methods),可以通过 this.props 访问到组件的属性(props)。
jsx复制
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
函数组件是一个纯函数,它接收一个 props 参数并返回一个 React 元素。函数组件没有自己的状态和生命周期方法,但是可以使用 React 提供的 Hook 来管理状态和实现副作用。
jsx复制
import React, { useState } from 'react';
function MyComponent(props) {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
类组件和函数组件的主要区别在于语法和特性。类组件使用 ES6 类语法,可以拥有自己的状态和生命周期方法;函数组件使用纯函数语法,可以使用 Hook 来管理状态和实现副作用。在 React 16.8 版本之前,函数组件没有自己的状态和生命周期方法,只能用来展示 UI;而在 React 16.8 版本之后,引入了 Hook,使得函数组件具有了更多的能力。