0
点赞
收藏
分享

微信扫一扫

【函数组件和类组件中使用TS】


初始化react开发为ts环境

// 本地先安装好typescript编译器  npm i -g typescript
yarn create react-app myappts --template typescript

【函数组件和类组件中使用TS】_react.js


最终初始化的目录结构

【函数组件和类组件中使用TS】_react.js_02


注:在react+ts工程中,如果是组件或方法有jsx语法,则文件扩展名一定要是.tsx扩展名,否则编译报错

  • react+js 项目中 组件 .js 也可以是 .jsx
  • react+ts 项目中 组件只能是 .tsx
  • src目录下面的所有的 .ts或.tsx都会编译为 .js 然后再说编译为给浏览器运行的程序,所以如果你在reac+ts项目中备份文件,则一定扩展名不能是 .js .jsx .ts .tsx

类组件中使用ts

interface Istate {
num:number
}
第一种
class App extends Component<{},Istate> {
state={
num:111
}
第二种
class App extends Component {

state={
num:111
} as

Home组件

<Home num={this.state.num} count={this.count}>HOME</Home>

先给类型才能用

  • 给props添加自定义属性的类型
  • 通过泛型给当前属性添加自定义属性的props类型 相当于在react+js中的prop-types定义
  • 今后在react+ts项目中,如果有自定义属性的存在, 请一定要提前在定义组件时把属性的类型指定好

通过这样的方式来规范这组件需要传入的值。

interface Iprops{
num:number,
count:(n:number) =>void,
//children:any ,
children: ReactNode
}

import React, { Component,PropsWithChildren } from 'react'
import {ReactNode} from 'react'

interface Iprops{
num:number,
count:(n:number) =>void,
children:ReactNode

}
class Home extends Component<PropsWithChildren<Iprops>>

【函数组件和类组件中使用TS】_react.js_03

在函数组件中使用ts

useState它会自动映射出对应的初始类型,无须指定
第一种方法:
接口的各个声明方法:

interface Iprops {
num: number,
addNum:(n:number)=>void,
children:any
}
export default function index(props:) {
let { num,addNum,children } = props
return (
<>
<h2>Home</h2>
<h3>home_{num}</h3>
<button onClick={e => {addNum(3) }}>HOME+++</button>
<h2>CHildren的数据{children}</h2>
</>
)
}

第二种方法:

import React, { FC,PropsWithChildren } from 'react'
interface Iprops {
num: number,
addNum:(n:number)=>void,
}
type IHome = PropsWithChildren<Iprops>

const Home:FC<IHome> = (props)=> {
let { num,addNum,children } = props
return (
<>
<h2>Home</h2>
<h3>home_{num}</h3>
<button onClick={e => {addNum(3) }}>HOME+++</button>
<h2>CHildren的数据{children}</h2>
</>
)
}
export default


举报

相关推荐

0 条评论