typescript 子组件中的类型useState设置器

mzsu5hc0  于 2023-06-24  发布在  TypeScript
关注(0)|答案(2)|浏览(146)

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

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

然后在Child组件中,我试图键入setter,但我看到以下错误。
类型“Dispatch< SetStateAction< string[] >>”不能分配给类型“()=> void”。
我的代码看起来像这样

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

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

jgwigjjp1#

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

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

beq87vna2#

const Parent = () => {
   const [myState, setMyState] = useState<YourType>({});
   return(
     <Child count={myState} setCount={setMyState} />
   );
}
import { Dispatch, SetStateAction } from 'react'

type Props = {
  count: YourType;
  setCount: Dispatch<SetStateAction<YourType>>;
}

const Child = ({ count, setCount }: Props) => {
  // works with
  setCount(newState)

  // also with
  setCount(oldState => {
    // ...
    return newState
  })
}

相关问题