天天看點

【函數元件和類元件中使用TS】

初始化react開發為ts環境

// 本地先安裝好typescript編譯器  npm i -g typescript
yarn create react-app myappts --template typescript      
【函數元件和類元件中使用TS】

最終初始化的目錄結構

【函數元件和類元件中使用TS】

注:在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】

在函數元件中使用ts

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      

繼續閱讀