React 类组件通过继承 Component 类并使用生命周期方法来管理组件状态与副作用。本文通过一个简单的计时器组件 Demo,展示类组件的核心概念:constructor 中初始化 state、componentDidMount 中启动定时器(每秒更新 seconds 状态)、componentWillUnmount 中清理定时器防止内存泄漏,以及 render 方法返回 JSX 视图。文件后缀使用 .jsx。
本文适用于理解 React 类组件基本写法的初学者。
shell*.jsx
javascriptimport React, {Component} from 'react';
class Timer extends Component {
constructor(props) {
super(props);
this.state = {seconds: 0};
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState(state => ({
seconds: state.seconds + 1,
}));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <h1>Seconds: {this.state.seconds}</h1>;
}
}


本文作者:Odboy
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC 4.0 BY-SA 许可协议。转载请注明出处!