React之hooks
官方内置 hooks
useState
在函数组件中管理数据状态
基本数据类型
import React from 'react'
export function App(props) {
const [count, setCount] = React.useState(0)
return (
<div className='App'>
<div>{count}</div>
<button onClick={() => setCount(() => count + 1)}>add</button>
<button onClick={() => setCount(count + 1)}>add</button>
<button onClick={() => setCount(c => c + 1)}>add</button>
</div>
)
}
主要注意的点是 setCount 可以传入相应数值或匿名函数,如上所示的都是可以实现对 count+1
对 象
这里主要针对复杂类型(数组,对象),示例:
import * as React from 'react'
export default function App(props) {
type User = {
name: string
age: number
}
const [user, setUser] = React.useState<User>({
name: 'kuizuo',
age: 20,
})
return (
<div className="App">
<div>{user.name}</div>
<div>{user.age}</div>
<button
onClick={() => {
setUser((obj) => ({
...obj,
name: '愧怍',
}))
}}
>
set name as 愧怍
</button>
</div>
)
}