当前位置:首页 > React

如何用ts写react的类组件

2026-01-26 07:24:09React

使用 TypeScript 编写 React 类组件

在 TypeScript 中编写 React 类组件需要明确组件的 propsstate 的类型,同时遵循 React 的生命周期方法。以下是具体实现方式:

定义组件 Props 和 State 类型

使用接口或类型别名定义 propsstate 的结构,确保类型安全。

interface MyComponentProps {
  title: string;
  initialCount?: number; // 可选属性
}

interface MyComponentState {
  count: number;
  isActive: boolean;
}

创建类组件

通过继承 React.Component 并传入 propsstate 的类型泛型来创建组件。

如何用ts写react的类组件

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 会检查属性是否符合定义。

如何用ts写react的类组件

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>Pprops 类型,Sstate 类型。
  • 状态初始化:直接通过 state 属性初始化,而非在构造函数中。
  • 事件绑定:使用箭头函数或手动绑定 this,避免方法中的 this 指向问题。

通过以上方式,可以充分利用 TypeScript 的类型检查能力,提升 React 类组件的代码健壮性。

标签: 如何用组件
分享给朋友:

相关文章

vue 组件实现

vue 组件实现

Vue 组件实现方法 单文件组件 (SFC) 使用 .vue 文件格式,包含模板、脚本和样式三部分: <template> <div class="example">{…

vue组件传值实现分页

vue组件传值实现分页

Vue组件传值实现分页的方法 在Vue中实现分页功能,通常需要父子组件之间的数据传递。以下是几种常见的传值方式: 使用props传递数据 父组件通过props向子组件传递当前页码和总页数等分页信息:…

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

实现拖拽组件嵌套的核心思路 Vue中实现拖拽组件嵌套需要结合拖拽库(如vuedraggable)和组件递归渲染。核心在于动态管理嵌套数据结构,并通过事件传递实现层级更新。 安装必要依赖 推荐使用vu…

uniapp 滑动组件

uniapp 滑动组件

uniapp 滑动组件实现方法 使用swiper组件 uniapp内置的swiper组件可以实现滑动效果,适用于轮播图或页面切换场景。 示例代码: <swiper :indicator-d…

Vue组件实现方法

Vue组件实现方法

Vue组件的基本实现 Vue组件是Vue.js的核心概念之一,允许将UI拆分为独立可复用的代码片段。组件的实现方式有多种,以下是常见的几种方法。 单文件组件(SFC) 单文件组件以.vue为后缀,将…

vue实现水印组件

vue实现水印组件

Vue 水印组件的实现方法 使用Canvas绘制水印 在Vue组件中通过Canvas动态生成水印图案,将其作为背景添加到目标元素上。 <template> <div ref=…