【问题标题】:type useState setter in child component在子组件中输入 useState setter
【发布时间】:2019-07-13 23:48:21
【问题描述】:

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

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

然后在Child 组件中,我尝试输入setter,但看到以下错误。

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

我的代码是这样的

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

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

【问题讨论】:

    标签: javascript reactjs typescript ecmascript-6 types


    【解决方案1】:

    您可以指定setCount prop 函数需要一个数字作为第一个参数,错误就会消失。

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

    【讨论】:

    • 我很想知道如何像 react 那样输入它。因为你不能只传递一个数字给原来的setter,你也可以传递一个函数来使用之前的状态来修改状态
    猜你喜欢
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2023-01-04
    • 2020-01-17
    相关资源
    最近更新 更多