React集成TS

本文详细介绍了如何在React项目中集成TypeScript,包括使用`create-react-app`创建TS项目,声明依赖包的类型文档,定义组件的状态和属性接口,以及在类和函数组件中使用`ref`。此外,还涵盖了React Router的静态和动态路由,以及Redux的状态管理和action定义。
摘要由CSDN通过智能技术生成

React集成


构建React-TS项目

create-react-app demo --template typescript



声明文档

当在ts项目中使用依赖包时需要声明文档

部分依赖包的声明文档在依赖包的根目录下 因此不需要额外下载

当需要声明文档时需要另外安装

npm i @types/jquery  # @types 是npm的一个分支,用来存放 *.d.ts文件声明文档



在React中使用TS


接口

类中的状态及属性接口

import { Component } from 'react'

// 定义状态接口
interface Istate {
  name:string,
  age:number
}

// 定义属性接口
interface Iprops{
  flag:boolean
}

// 继承React组件时定义泛型 第一个参数为属性props的接口 第二个参数为状态state的接口 不需要时定义为any
class Test extends Component<Iprops,Istate> {
  state = {
    name: 'zs',
    age: 18
  }
  fn = () => {
    // 定义状态接口后 对状态的修改会进行检查
    this.setState({ name: 'ww' },() => {
      console.log(this.state.name.substring(0,1))  
    }) 
  }
  render() {
    return (
      <div>test
        <button onClick={this.fn}>change</button>
      </div>
    )
  }
}

// 父组件
export default class Test2 extends Component<any,any>{
  render(){
  // 定义属性接口后 对属性的传递进行检查
    return <Test flag={true}></Test>
  }
}


函数中的状态及属性接口


import { useState } from "react"

// 定义属性接口
interface Iprops {
  name:string
}

//----------------------命名函数组件中--------------------------------

// 在函数组件的props传参中对props定义接口
export default function Test(props:Iprops) {

// 定义属性接口只需在useState时定义泛型即可
  const [show, setShow] = useState<boolean>(true)
  
  return (
    <div>test-{props.name}</div>
  )
}

//----------------------匿名函数组件中--------------------------------

// 通过React.FC定义泛型实现props接口
const Test:React.FC<Iprops> = (props) => {
  return <div>test-{props.name}</div>
}



ref

类组件中创建引用对象

export default class test extends Component<any, any> {

   // ts中创建input引用对象需要规定泛型HTMLInputElement  div则为HTMLDivElement...
  myref = React.createRef<HTMLInputElement>()
  
  componentDidMount() {
  // 需要使用引用input的值时因为TS不确认是否为空 因此需要类型断言
    console.log((this.myref.current as HTMLInputElement).value)
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.myref} />
      </div>
    )
  }
}

函数组件中创建引用对象

import { useEffect, useRef } from 'react'

export default function Test() {
 // ts函数组件中创建input引用对象需要规定泛型HTMLInputElement 且必须为null
  const myref = useRef<HTMLInputElement>(null)
  useEffect(() => {
    console.log((myref.current as HTMLInputElement).value)
  },[])
  return (
    <div>
      <input type="text" ref={myref} />
    </div>
  )
}



route

TS中路由的使用

//--------------------------------静态路由跳转----------------------------
import { Component } from 'react'
import { BrowserRouter, Route, RouteComponentProps} from 'react-router-dom'

// 子组件中要使用路由对象上的属性需要实现属性接口 属性接口为react-router-dom中的RouteComponentProps
class Test1 extends Component<RouteComponentProps,any> {
  componentDidMount() { 
  // 实现接口后才能使用路由参数
    console.log(this.props.history)
  }
  render() {
    return (
      <div>test</div>
    )
  }
}

// 路由父组件
export default class Test extends Component<any,any> {
  render() {
    return (
      <BrowserRouter>
          <Route path='/test' component={Test1}></Route>
      </BrowserRouter> 
    )
  }
}

//-------------------------动态路由参数-----------------------------

import { Component } from 'react'
import { BrowserRouter, Route, RouteComponentProps} from 'react-router-dom'

// 动态路由的参数接口
interface IParam {
	myid:string
}

// 需要在实现路由属性的泛型上定义泛型接口
class Test1 extends Component<RouteComponentProps<IParam>,any> {
  componentDidMount() { 
  // 实现路由属性泛型接口后才能检查动态路由参数
    console.log(this.props.match.params.myid))
  }
  render() {
    return (
      <div>test</div>
    )
  }
}

// 路由父组件
export default class Test extends Component<any,any> {
  render() {
    return (
      <BrowserRouter>
      // 动态路由参数
          <Route path='/test:myid' component={Test1}></Route>
      </BrowserRouter> 
    )
  }
}



redux

import { createStore } from 'redux'

// 定义action接口
interface Iaction {
  type:string,
  payload?:any
}
// 定义state接口
interface Istate {
  show:boolean
}

// 实现状态接口以及action接口
const reducer = (prevState:Istate = {
  show:true
}, actions:Iaction) => {
  return prevState
}

const store = createStore(reducer)

export default store
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Raccom

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

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

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

打赏作者

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

抵扣说明:

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

余额充值