useState 中使用 ts
tsx
type User = {
name: string
age: number
}
function App() {
// 直接使用对象
// const [user, setUser] = useState<User | null>(null)
// const [user, setUser] = useState<User>({
// name: 'jack',
// age: 18
// })
// 使用函数返回对象
const [user, setUser] = useState<User>(()=> {
return {
name: 'jack',
age: 18
}
})
// setUser 也同理有 直接修改 和 使用函数返回对象 的修改形式
return (
<>this is an app</>
)
}
export default App
props 中使用 ts
tsx
type Props = {
className: string
children: React.ReactNode
}
function Button(props: Props) {
const {className, children} = props
return <button className={className}>{children}</button>
}
tsx
type Props = {
onGetMsg?: (msg: string) => void
}
function Button(props: Props) {
const {onGetMsg} = props
const clickHandler = () => {
onGetMsg?.('hello')
}
return <button onClick={clickHandler}>sendMsg</button>
}
function App() {
return (
<>
{/*内联函数会自动进行类型推导,如果是外部函数 还需要手动进行类型约束*/}
<Button onGetMsg={(msg) => console.log(msg)}/>
</>
)
}
export default App
useRef 使用 ts
tsx
function App() {
const domRef = useRef<HTMLInputElement>(null)
useEffect(() => {
console.log(domRef.current?.value)
}, []);
return (
<>
<input ref={domRef}/>
</>
)
}
export default App
tsx
function App() {
const timerRef = useRef<number | undefined>(undefined)
useEffect(() => {
timerRef.current = setInterval(() => {
console.log('1')
}, 1000)
return ()=> clearInterval(timerRef.current)
}, []);
return (
<>this is div</>
)
}