Typescript: React event types

前端 未结 8 898
故里飘歌
故里飘歌 2020-11-27 11:50

What is the correct type for React events. Initially I just used any for the sake of simplicity. Now, I am trying to clean things up and avoid use of any<

8条回答
  •  余生分开走
    2020-11-27 12:25

    I have the following in a types.ts file for html input, select, and textarea:

    export type InputChangeEventHandler = React.ChangeEventHandler
    export type TextareaChangeEventHandler = React.ChangeEventHandler
    export type SelectChangeEventHandler = React.ChangeEventHandler
    

    Then import them:

    import { InputChangeEventHandler } from '../types'
    

    Then use them:

    
    const updateName: InputChangeEventHandler = (event) => {
      // Do something with `event.currentTarget.value`
    }
    const updateBio: TextareaChangeEventHandler = (event) => {
      // Do something with `event.currentTarget.value`
    }
    const updateSize: SelectChangeEventHandler = (event) => {
      // Do something with `event.currentTarget.value`
    }
    

    Then apply the functions on your markup (replacing ... with other necessary props):