在打字稿中将 useState 作为道具传递 [英] Passing useState as props in typescript
问题描述
假设我有一个带有两个子组件的父组件:
Say I have a parent component with two child components:
const Parent = () => {
const [myVar, setmyVar] = useState(false)
return (
<>
<MyChildComponent1 myVar={myVar} setMyVar={setMyVar} \>
<MyChildComponent2 myVar={myVar} \>
</>
)
}
现在如何在 MyChildComponent2
中正确设置类型?
Now how would I go about setting the type correctly in MyChildComponent2
?
这是我目前想到的:
const MyChildComponent1 = (
{myVar, setMyVar}:
{myVar: boolean, setMyVar: (value: boolean) => void}) = (...)
setMyvar
的类型是否正确?或者应该是别的什么?
Is the type for setMyvar
correct? Or should it be something else?
推荐答案
与调用 useState
返回的函数相匹配的类型将是:
The type that would match the function returned from invoking useState
would be:
setMyVar: (value: boolean | ((prevVar: boolean) => boolean)) => void;
如果我们查看DefinitelyTyped
[1]中的类型定义文件,我们可以看到返回类型中的第二个类型是调度:
If we look at the type definition file from DefinitelyTyped
[1], we can see that the second type in the return type is a dispatch:
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
因此将提供的泛型类型传递给 SetStateAction
,其定义为:
Thus the generic type provided is passed through to SetStateAction<S>
, which is defined as:
type SetStateAction<S> = S | ((prevState: S) => S);
从本质上讲,您的组件的界面如下所示:
So essentially, an interface for your component would be the following:
interface IProps {
myVar: boolean;
setMyVar?: (value: boolean | (prevVar: boolean) => boolean) => void;
}
正如@Retsam 所说,最好使用 React 的导出类型:
As @Retsam said, it's best to use React's exported types:
import { Dispatch, SetStateAction } from "react";
interface IProps {
myVar: boolean;
setMyVar?: Dispatch<SetStateAction<boolean>>;
}
参考资料:[1] https://github.com/absoluteTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L845
这篇关于在打字稿中将 useState 作为道具传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!