在子组件中键入useState setter

时间:2019-02-20 10:12:28

标签: javascript reactjs typescript ecmascript-6 types

我正在尝试将useState设置器传递给子组件,但不确定如何键入。

const Parent = () => {
   const [count, setCount] = useState(0);
   return(
     Child count={count} setCount={setCount} />
   );
}

然后在Child组件中,我试图键入设置器,但看到以下错误。

  

类型'Dispatch >'不可分配给类型'()=> void'。

我的代码如下

type Props = {
  count: number;
  // the issue is the line below
  setCount: () => void;
}

const Child = ({ count, setCount }: Props) => {
    .... code here
}

1 个答案:

答案 0 :(得分:2)

您可以指定setCount prop函数将数字作为第一个参数,并且错误将消失。

type Props = {
  count: number;
  setCount: (num: number) => void;
}