props与ts

5 阅读1分钟

为Props添加类型

props作为React组件的参数入口,添加了类型之后可以限制参数输入以及在使用props有良好的类型提示

使用interface接口

interface Props {
  className: string
}
​
export const Button = (props:Props)=>{
  const { className } = props
  return <button className={ className }>Test</button>
}
​
function App(){
    return (
        <>
            <Button className="test" />
        </>
    )
}

使用自定义类型Type

type Props =  {
  className: string
}
​
export const Button = (props:Props)=>{
  const { className } = props
  return <button className={ className }>Test</button>
}

为Props的chidren属性添加类型

children是-个比较特殊的prop,支持多种不同类型数据的传入,需要通过一个内置的ReactNode类型来做注解 (感觉类似于插槽)

type Props = {
  children: React.ReactNode
}
​
export const Button = (props: Props)=>{
   const { children } = props
   return <button>{ children }</button>
}
​
function App(){
    return (
        <>
            <Button className="test">click me!</Button>
            <Button className="test">
                <span>this is span</span>
            </Button>
        </>
    )
}

:::warning 说明:React.ReactNode是一个React内置的联合类型,包括 React.ReactElementstringnumber React.ReactFragmentReact.ReactPortalbooleannullundefined :::

为事件prop添加类型

// props + ts
type Props = {
  onGetMsg?: (msg: string) => void
}
​
function Son(props: Props) {
  const { onGetMsg } = props
  const clickHandler = () => {
    onGetMsg?.('this is msg')
  }
  return <button onClick={clickHandler}>sendMsg</button>
}
​
function App() {
  const getMsgHandler = (msg: string) => {
    console.log(msg)
  }
  return (
    <>
      <Son onGetMsg={(msg) => console.log(msg)} />
      <Son onGetMsg={getMsgHandler} />
    </>
  )
}
​
export default App

为事件handle添加类型

为事件回调添加类型约束需要使用React内置的泛型函数来做,比如最常见的鼠标点击事件和表单输入事件:

function App(){
  const changeHandler: React.ChangeEventHandler<HTMLInputElement> = (e)=>{
    console.log(e.target.value)
  }
  
  const clickHandler: React.MouseEventHandler<HTMLButtonElement> = (e)=>{
    console.log(e.target)
  }
​
  return (
    <>
      <input type="text" onChange={ changeHandler }/>
      <button onClick={ clickHandler }> click me!</button>
    </>
  )
}