TypeScript 与 React 开发实战指南

TypeScript 与 React 开发实战指南

TypeScript-Handbook Deprecated, please use the TypeScript-Website repo instead TypeScript-Handbook 项目地址: https://gitcode.com/gh_mirrors/ty/TypeScript-Handbook

TypeScript 作为 JavaScript 的超集,为 React 开发带来了类型安全和更好的开发体验。本文将详细介绍如何从零开始搭建一个 TypeScript + React 的开发环境,并逐步实现一个完整的应用开发流程。

项目初始化

创建 TypeScript React 项目

使用 create-react-app 工具可以快速搭建 React 项目,通过指定 react-scripts-ts 参数可以集成 TypeScript 支持:

npx create-react-app my-app --scripts-version=react-scripts-ts

项目目录结构如下:

my-app/
├─ .gitignore
├─ node_modules/
├─ public/
├─ src/
│  └─ ...
├─ package.json
├─ tsconfig.json
└─ tslint.json

关键文件说明:

  • tsconfig.json:TypeScript 编译配置
  • tslint.json:代码风格检查配置
  • package.json:项目依赖和脚本命令

开发流程

启动开发服务器

npm run start

这个命令会启动开发服务器,默认在 http://localhost:3000 打开应用,并支持热重载。

运行测试

npm run test

使用 Jest 测试框架运行所有 .test.ts.spec.ts 结尾的测试文件。

构建生产版本

npm run build

生成优化后的静态资源文件,位于 build/static 目录下。

组件开发实战

创建 Hello 组件

我们来开发一个简单的 Hello 组件,它接收两个 props:

  • name:必填的字符串
  • enthusiasmLevel:可选的数字,表示感叹号数量

组件实现 (src/components/Hello.tsx):

import * as React from 'react';

export interface Props {
  name: string;
  enthusiasmLevel?: number;
}

function Hello({ name, enthusiasmLevel = 1 }: Props) {
  if (enthusiasmLevel <= 0) {
    throw new Error('热情度必须大于0');
  }

  return (
    <div className="hello">
      <div className="greeting">
        Hello {name + getExclamationMarks(enthusiasmLevel)}
      </div>
    </div>
  );
}

function getExclamationMarks(numChars: number) {
  return Array(numChars + 1).join('!');
}

export default Hello;

组件使用

在入口文件 (index.tsx) 中使用组件:

import Hello from './components/Hello';

ReactDOM.render(
  <Hello name="TypeScript" enthusiasmLevel={3} />,
  document.getElementById('root') as HTMLElement
);

注意这里的类型断言 as HTMLElement,它告诉 TypeScript 我们知道 getElementById 会返回一个有效的 HTMLElement。

样式与测试

添加样式

创建 Hello.css 文件并导入:

import './Hello.css';

编写测试

使用 Enzyme 测试组件行为 (Hello.test.tsx):

import * as React from 'react';
import * as enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Hello from './Hello';

enzyme.configure({ adapter: new Adapter() });

it('默认显示1个感叹号', () => {
  const wrapper = enzyme.shallow(<Hello name='张三' />);
  expect(wrapper.find(".greeting").text()).toBe('Hello 张三!')
});

it('显示指定数量的感叹号', () => {
  const wrapper = enzyme.shallow(<Hello name='李四' enthusiasmLevel={3}/>);
  expect(wrapper.find(".greeting").text()).toBe('Hello 李四!!!')
});

it('热情度为0时抛出错误', () => {
  expect(() => {
    enzyme.shallow(<Hello name='王五' enthusiasmLevel={0} />);
  }).toThrow();
});

状态管理进阶

引入 Redux

安装 Redux 相关依赖:

npm install redux react-redux @types/react-redux

定义应用状态

创建状态类型定义 (src/types/index.tsx):

export interface StoreState {
    languageName: string;
    enthusiasmLevel: number;
}

创建 Action

定义 action 类型和创建函数 (src/actions/index.tsx):

import * as constants from '../constants'

export interface IncrementEnthusiasm {
    type: constants.INCREMENT_ENTHUSIASM;
}

export interface DecrementEnthusiasm {
    type: constants.DECREMENT_ENTHUSIASM;
}

export type EnthusiasmAction = IncrementEnthusiasm | DecrementEnthusiasm;

export function incrementEnthusiasm(): IncrementEnthusiasm {
    return { type: constants.INCREMENT_ENTHUSIASM }
}

export function decrementEnthusiasm(): DecrementEnthusiasm {
    return { type: constants.DECREMENT_ENTHUSIASM }
}

实现 Reducer

创建 reducer 处理状态变更 (src/reducers/index.tsx):

import { EnthusiasmAction } from '../actions';
import { StoreState } from '../types/index';
import { INCREMENT_ENTHUSIASM, DECREMENT_ENTHUSIASM } from '../constants/index';

export function enthusiasm(state: StoreState, action: EnthusiasmAction): StoreState {
  switch (action.type) {
    case INCREMENT_ENTHUSIASM:
      return { ...state, enthusiasmLevel: state.enthusiasmLevel + 1 };
    case DECREMENT_ENTHUSIASM:
      return { ...state, enthusiasmLevel: Math.max(1, state.enthusiasmLevel - 1) };
  }
  return state;
}

总结

通过本文,我们学习了:

  1. 如何搭建 TypeScript + React 开发环境
  2. 开发类型安全的 React 组件
  3. 为组件添加样式和测试
  4. 使用 Redux 进行状态管理

TypeScript 为 React 开发带来了诸多优势:

  • 组件 Props 和 State 的类型检查
  • 更好的代码提示和自动补全
  • 减少运行时错误
  • 更易于维护的大型项目

希望这篇指南能帮助你顺利开始 TypeScript 和 React 的开发之旅!

TypeScript-Handbook Deprecated, please use the TypeScript-Website repo instead TypeScript-Handbook 项目地址: https://gitcode.com/gh_mirrors/ty/TypeScript-Handbook

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梅俐筝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值