我正在用 TypeScript 编写 React 组件的前端测试。由于代码来自更有经验的程序员,因此某些数据类型对我来说似乎有点新。现在我有了一个用“Dispatch”定义的道具作为数据类型。我注意到使用 useState-Hook 的 set-property 是有效的,但我不太确定这是否是应该使用 prop 的方式。供参考:该道具称为“onFullScreenClick”。我将非常感谢您对最有可能放入的内容进行解释和示例
I am writing Frontend Tests for React Components in TypeScript. Since the Code is from a more experienced Programmer, some Datatypes seem a bit new for me. Now I've got a prop that is defined with "Dispatch<SetStateAction>" as datatype. I've noticed that using the set-property of a useState-Hook is working, but I'm not really sure if this is how the prop is supposed to be used. For reference: The prop is called "onFullScreenClick". I'd be very grateful for an explanation and an example for what's most likely to be put in
发布评论
评论(2)
如果您查看类型的来源:
Dispatch
将操作作为参数并返回任何有意义的内容 (void)。操作有多种类型,
SetStateAction
就是其中之一。请记住,useState 可以采用新状态,或者采用先前状态并返回新状态的函数。
所以
useState
的类型实际上是:If you look at the source of the typings:
Dispatch
takes an action as a parameter and returns nothing meaningful (void).There are multiple types of actions, and one of them is
SetStateAction
.Remember that
useState
can take a new state, or a function that takes the previous state and returns the new state.So
useState
's type is actually:这只是告诉打字稿的一种方式,我们传入的道具的类型
看看这个简单的计数器 来自沙箱的示例
我们在父级中有
const [num, setnum] = useState(0)
,并且我们将状态和 setter 函数传递给子级componentnum
的类型是从useState(0)
推断出来的,如果我们想要 setter 函数的类型,我们只需将鼠标悬停在它上面,我们就会得到const setNum: Dispatch>
而这个
Dispatch>
是 setter 函数的类型。It's just a way telling typescript, the type of the props we are passing in
Take a look at this simply counter example from sandbox
We have
const [num, setnum] = useState(0)
in the parent, and we pass both state and setter function to child componentThe type of the
num
is infered fromuseState(0)
, if we want the type of the setter function, we just hover mouse over it, and we getconst setNum: Dispatch<SetStateAction<number>>
and this
Dispatch<SetStateAction<number>>
is the type of setter function.