在打字稿中传递useState作为道具

时间:2019-05-07 18:36:19

标签: reactjs typescript react-hooks react-props

说我有一个带有两个子组件的父组件:

const Parent = () => {
   const [myVar, setmyVar] = useState(false)

   return (
     <>
       <MyChildComponent1 myVar={myVar} setMyVar={setMyVar} \> 
       <MyChildComponent2 myVar={myVar} \>
     </>
   )
}

现在我该如何在MyChildComponent2中正确设置类型?

这是我到目前为止提出的:

const MyChildComponent1 = (
  {myVar, setMyVar}: 
  {myVar: boolean, setMyVar: (value: boolean) => void}) = (...)

setMyvar的类型正确吗?还是其他?

3 个答案:

答案 0 :(得分:3)

调度和SetStateAction类型

如@Retsam所述,您还可以从React导入和使用类型DispatchSetStateAction

import React, { Dispatch, SetStateAction } from 'react';

const MyChildComponent1 = (
  myVar: boolean,
  setMyVar: Dispatch<SetStateAction<boolean>>
) => {...};

奖金

当我经常使用它时,我会创建一个类型别名以帮助提高可读性

import React, { Dispatch, SetStateAction } from 'react';

type Dispatcher<S> = Dispatch<SetStateAction<S>>;

const MyChildComponent1 = (
  myVar: boolean,
  setMyVar: Dispatcher<boolean>,
) => {...};

希望这会有所帮助。

答案 1 :(得分:2)

与调用Plotly.purge(rootScatter);返回的函数相匹配的类型为:

useState

如果我们查看setMyVar: (value: boolean | ((prevVar: boolean) => boolean)) => void; [1]中的类型定义文件,则可以看到返回类型中的第二个类型是分派:

DefinitelyTyped

因此,提供的通用类型将传递给function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>]; ,它被定义为:

SetStateAction<S>

因此,从本质上讲,组件的接口如下:

type SetStateAction<S> = S | ((prevState: S) => S);

参考: [1] https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L845

答案 2 :(得分:2)

在@fiz的评论中,他的代码阻止了我的工作:

import React, { Dispatch, SetStateAction } from 'react';

const MyChildComponent1 = (
  myVar: boolean,
  setMyVar: Dispatch<SetStateAction<<boolean>>
) => {...};

我必须设置setMyVar: Dispatch<SetStateAction<boolean>>(方括号太多)