React 中的 ts 标注
useState 标注
自动推导
泛型支持
初始值 null
Props 标注
基础使用
为 props.children 标注类型
说明:注解之后,children 可以是多种类型,包括:React.ReactNode: React.ReactElement、React.ReactFragment、React.ReactPortal、boolean、、string、number、null、undefined
tsx
type Props = {
children: React.ReactNode
}
function Button(props: Props) {
const { children } = props
return <button>{props.children}</button>
}
为事件 prop 标注类型
说明:
- 在组件内部调用时需要遵守类型的约束,参数传递需要满足要求
- 绑定 prop 时,如果绑定内联函数直接可以推断出参数类型,否则需要单独注解匹配的参数类型
tsx
type Props = {
onGetMsg?: (msg: string) => void
}
function Button(props: Props) {
const { children } = props
return <button>{props.children}</button>
}
useRef 标注
获取 DOM 的场景, 可以直接把要获取的 dom 元素的类型当成泛型参数传递给 useRef, 可以推导出 .current
属性的类型
tsx
function App() {
const domRef = useRef<HTMLInputElement>(null)
useEffect(() => {
domRef.current?.focus()
})
return <input ref={domRef} />
}
引用稳定的存储器
把 useRef
当成引用稳定的存储器使用的场景,可以通过泛型传入联合类型来做,比如定时器的场景:
tsx
function App() {
const timerRef = useRef<number | undefined>(undefined)
useEffect(() => {
timerRef.current = window.setTimeout(() => {
console.log('timer 1')
}, 1000)
return () => clearInterval(timerRef.current)
})
}