繁体   English   中英

如何在`React.useState`中添加类型表示法?

[英]How to add type notation to `React.useState`?

我正在使用带有钩子的React 16.8.3,目前我想键入React.useState

type Mode = 'confirm' | 'deny'  
type Option = Number | null

const [mode, setMode] = React.useState('confirm')
const [option, setOption] = React.useState(100)

使用我当前的代码, modestring类型,而我想要的是Mode类型。 Option相同的问题。

如何向React.useState添加类型表示法?

React.useState使用泛型,因此您可以通过以下方式在其中添加类型表示法:

const [mode, setMode] = React.useState<Mode>('confirm')
const [option, setOption] = React.useState<Option>(100)

仅供参考... React.useState类型定义:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM