day11-03.Component与TypeScript

为Props添加类型

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

使用interface接口

interface Props {
  className: string
}

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

使用自定义类型Type

type Props =  {
  className: string
}

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

为Props的chidren属性添加类型

children属性和props中其他的属性不同,它是React系统中内置的,其它属性我们可以自由控制其类型,children属性的类型最好由React内置的类型提供,兼容多种类型

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

为事件prop添加类型

为事件handle添加类型

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

Last updated

Was this helpful?