react类组件实现
React 类组件的基本结构
类组件是 React 中通过 ES6 类定义的组件,继承自 React.Component 或 React.PureComponent。以下是一个基础示例:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return <div>Count: {this.state.count}</div>;
}
}
生命周期方法
类组件提供了一系列生命周期方法,用于在不同阶段执行逻辑:
-
挂载阶段
componentDidMount():组件插入 DOM 后调用,适合发起网络请求或订阅事件。 -
更新阶段
shouldComponentUpdate(nextProps, nextState):决定是否重新渲染,默认返回true。componentDidUpdate(prevProps, prevState):组件更新后调用,可操作 DOM 或发送请求。 -
卸载阶段
componentWillUnmount():组件移除前调用,用于清理定时器或取消订阅。
状态管理
通过 this.state 定义组件内部状态,使用 this.setState() 更新状态:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<button onClick={this.increment}>+</button>
<span>{this.state.count}</span>
</div>
);
}
}
事件处理
类组件中事件处理函数需绑定 this,推荐在构造函数中使用 bind 或使用箭头函数:
class EventExample extends React.Component {
handleClick = () => {
console.log('Clicked');
};
render() {
return <button onClick={this.handleClick}>Click</button>;
}
}
Props 接收
通过 this.props 访问父组件传递的属性:

class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
与函数组件的对比
-
类组件特点
支持生命周期方法和内部状态管理。
适用于复杂逻辑或需要精细控制生命周期的场景。 -
函数组件特点
通过 Hooks(如useState、useEffect)实现类似功能,代码更简洁。
React 官方推荐优先使用函数组件。
完整示例
以下是一个整合状态、生命周期和事件的类组件示例:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState({ seconds: this.state.seconds + 1 });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div>Seconds: {this.state.seconds}</div>;
}
}






