如何用ts写react的类组件
使用 TypeScript 编写 React 类组件
在 TypeScript 中编写 React 类组件需要明确组件的 props 和 state 的类型,同时遵循 React 的生命周期方法。以下是具体实现方式:
定义组件 Props 和 State 类型
使用接口或类型别名定义 props 和 state 的结构,确保类型安全。
interface MyComponentProps {
title: string;
initialCount?: number; // 可选属性
}
interface MyComponentState {
count: number;
isActive: boolean;
}
创建类组件
通过继承 React.Component 并传入 props 和 state 的类型泛型来创建组件。

class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
// 初始化 state
state: MyComponentState = {
count: this.props.initialCount || 0,
isActive: false,
};
// 生命周期方法(可选)
componentDidMount() {
console.log('Component mounted');
}
// 事件处理方法
handleClick = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
isActive: !prevState.isActive,
}));
};
// 渲染方法
render() {
const { title } = this.props;
const { count, isActive } = this.state;
return (
<div>
<h1>{title}</h1>
<p>Count: {count}</p>
<p>Status: {isActive ? 'Active' : 'Inactive'}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
默认 Props 设置
通过静态属性 defaultProps 定义默认值,需在类外部声明类型。
MyComponent.defaultProps = {
initialCount: 10,
};
使用组件
在父组件中传递类型化的 props,TypeScript 会检查属性是否符合定义。

const App = () => {
return <MyComponent title="Counter App" initialCount={5} />;
};
处理事件类型
为事件处理函数明确指定事件类型,例如 React.MouseEvent。
handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ inputValue: e.target.value });
};
完整示例
结合上述内容,以下是一个完整的计数器组件示例:
import React from 'react';
interface CounterProps {
initialValue?: number;
}
interface CounterState {
count: number;
}
class Counter extends React.Component<CounterProps, CounterState> {
state: CounterState = {
count: this.props.initialValue || 0,
};
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Current Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
Counter.defaultProps = {
initialValue: 0,
};
export default Counter;
注意事项
- 泛型参数顺序:
React.Component<P, S>中P是props类型,S是state类型。 - 状态初始化:直接通过
state属性初始化,而非在构造函数中。 - 事件绑定:使用箭头函数或手动绑定
this,避免方法中的this指向问题。
通过以上方式,可以充分利用 TypeScript 的类型检查能力,提升 React 类组件的代码健壮性。






