最佳答案
有没有可能使用 function
作为我的反应元件的状态?
示例代码:
// typescript
type OoopsFunction = () => void;
export function App() {
const [ooops, setOoops] = React.useState<OoopsFunction>(
() => console.log('default ooops')
);
return (
<div>
<div onClick={ ooops }>
Show Ooops
</div>
<div onClick={() => {
setOoops(() => console.log('other ooops'))
}}>
change oops
</div>
</div>
)
}
但是它不工作... defaultOoops
将在一开始被调用,当单击 change oops
时,otrher ooops
将被立即记录到控制台,而不是在再次单击 Show Ooops
后进行日志记录。
为什么?
是否可以使用函数作为组件的状态?
否则反应有其特殊的方法来处理这样的 the function state
?