You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JavaScript编写的React计数器组件转换为TypeScript版本

React JavaScript计数器组件转TypeScript实现

核心修改规范

  • TypeScript版本的React类组件需要显式声明Props和State两个泛型参数,提前定义对应的类型接口
  • 若组件不需要接收外部传入的属性,Props接口可以定义为空
  • State接口需要明确声明每个状态字段的类型,本次案例中count字段为数字类型
  • 可以将类方法改为箭头函数,自动绑定this,避免每次render时重复绑定,也能降低类型报错概率

完整转换后的代码

import React, { Component } from "react";
import { Box, Button } from "@material-ui/core";

// 定义组件Props类型,无外部传入属性时留空即可
interface CounterProps {}
// 定义组件State类型,明确字段类型
interface CounterState {
  count: number;
}

class Counter extends Component<CounterProps, CounterState> {
  constructor(props: CounterProps) {
    super(props);
    this.state = {
      count: 5,
    };
  }

  // 箭头函数自动绑定this,无需额外bind处理
  increment = () => {
    this.setState({
      count: this.state.count + 1,
    });
  };

  decrement = () => {
    this.setState({
      count: this.state.count - 1,
    });
  };

  render() {
    return (
      <div>
        <Button variant="contained" color="primary" size="large" onClick={this.increment}>
          +
        </Button>
        <Box component="span" margin={5}>
          {this.state.count}
        </Box>
        <Button variant="contained" color="primary" size="large" onClick={this.decrement}>
          -
        </Button>
      </div>
    );
  }
}

export default Counter;

注意事项

  • 转换后的文件后缀需要修改为.tsx,才能同时支持TS语法和JSX语法
  • 如果需要保留原代码的bind写法,无需修改方法定义,仅补充泛型声明和类型接口即可正常运行

内容的提问来源于stack exchange,提问作者Yjin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 17:24:03