当前位置:首页 > 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实现组件缓存的方法 在Vue中实现组件缓存可以通过内置的<keep-alive>组件完成,该组件能够缓存不活动的组件实例,避免重复渲染。 使用<keep-alive>基…

vue实现tooltips组件

vue实现tooltips组件

实现基础 Tooltip 组件 创建一个名为 Tooltip.vue 的单文件组件,包含模板、样式和逻辑: <template> <div class="tooltip-con…

vue抽屉组件实现

vue抽屉组件实现

Vue 抽屉组件实现 使用 Element UI 实现 Element UI 提供了现成的抽屉组件 el-drawer,可以快速实现抽屉效果。 安装 Element UI: npm install…

vue 实现toast组件

vue 实现toast组件

实现 Vue Toast 组件的方法 创建基础 Toast 组件 在 Vue 项目中创建一个基础 Toast 组件,通常包含消息内容和显示控制逻辑。 <template> &…

react如何引入组件

react如何引入组件

引入组件的常见方法 直接导入组件文件 通过import语句从指定路径引入组件文件,适用于项目内自定义组件。假设组件文件位于./components/Button.js: import Button…

vue实现弹窗组件

vue实现弹窗组件

实现弹窗组件的基本结构 在Vue中创建一个弹窗组件通常需要三个核心部分:组件模板、样式和逻辑控制。弹窗组件应具备打开、关闭功能,并支持内容插槽或属性传入。 <template> &l…