项目经验:react中使用typescript

本文介绍了在React中使用TypeScript的实践经验,包括类组件、函数组件、Hook的使用,以及React中的类型约束和Promise类型的应用。同时,提供了TS实现Context和Button组件的示例,帮助开发者更好地在项目中应用TypeScript。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

如果你学会了,可以忽略本文章,或去项目经验地图寻找更多答案


使用规则

在 react 中使用 ts 的几点原则和变化:

  • 所有用到jsx语法的文件都需要以tsx后缀命名
  • 全局变量或者自定义的window对象属性,统一在项目根下的global.d.ts中进行声明定义
  • 对于项目中常用到的接口数据对象,在types/目录下定义好其结构化类型声明

类组件

interface HelloProps{
   
  name:string,
  age:number,
}

interface HelloState{
   
  msg: string,
}

class Comments extends PureComponent<HelloProps, HelloState>{
   
  constructor(props: HelloProps){
   
    super(props)
    this.state = {
   
        mag:'hello ts'
    } 
  }
  render(){
   
       return (
           <div>
               <p>{
   this.state.msg}</p>
               <p>你好,我是{
   this.props.name},我今年{
   this.props.age}</p>
           </div>
      )
  }
}

函数组件

import React from 'react';

interface HelloProps{
   
   name:string,
   age:number
}


几种写法:
const App = (props: HelloProps) => {
   }
const Hello: React.FunctionComponent<HelloProps> = () => {
   }
const Hello: React.FC<HelloProps> = ({
    name,age}) => {
   
 return (
      <div>
           你好,我是{
   name},我今年{
   age}
      </div>
   )
}

hook

限制类型类型
const [error, setError] = useState<Error | null>(null)

空数组:如果不限制是never[] 类型
const [arr, setArr] = useState([])  //arr 是 never[] 类型
const [arr, setArr] = useState<number[]>([])



自定义hook使用泛型
interface State<D> {
   
	error: Error | null;
    data: D | null;
    status: 'idle' | 'loading' | 'error' | 'success';
}

封装
export const useAsync = <D>(initialState?: State<D>) => {
   
    const [state, setState] = useState<State<D>>(
        {
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值