在react中使用typescript并不是了解了typescript的语法就能信手拈来,而是需要直到很多其他的特性。
React原始类型
1. React.HTMLAttributes
如果需要封装一个Button的UI组件,那么就需要支持所有的button按钮原来的React DOM属性,比如disabled,比如onClick, onMouseDown, onMouseUp等等。
这个类型是个范式,可以传入一个参数,获得各种各样的原始React DOM属性。
interface Props {
round?: boolean
size?: string
animation?: string
full: boolean
}
type ButtonProps = Props & React.HTMLAttributes<HTMLButtonElement>
2. React.ReactElement
如果使用children之类功能,就需要支持react的React DOM的属性。
比如Tabs的children是其他的Tab
interface TabsProps {
active: boolean
value: number | string
className: string
children: React.ReactElement[]
onChange: (value: number | string, index: number) => void
}
3. createRef
使用ref也需要返回,ref需要根据不同的范型返回不同的dom的原始类型,需要使用下边这种方式去写,如果ref的是React的Component,需要自定义范型。
tab = React.createRef<HTMLDivElement>()
未完待续
嗨,请先 登录