【问题标题】:issue with passing hook to child typescript将钩子传递给子打字稿的问题
【发布时间】:2019-07-01 16:46:15
【问题描述】:

我有一个使用钩子的反应组件。我的父组件如下所示:

const Parent = () => {

   const [isActive, setIsActive] = useState(false);

   return (
     <Child isActive={isActive} setIsActive={setIsActive} />
   );
}

这是子组件

type Props = {
   isActive: boolean;
   setIsActive: () => void;
}
const Child = ({ isActive, setIsActive}: Props) {
   // component
} 

我看到的错误是

类型错误:类型“Dispatch ”不可分配给 > 类型“() => void”。 TS2322

【问题讨论】:

  • setIsActive 函数应始终为 isActive 返回新状态。所以,你不能使用 type () => void; void 表示,您没有返回值。尝试通过任何(或 isActive 类型)来修复 void。

标签: javascript reactjs typescript ecmascript-6


【解决方案1】:

ChildProps 类型不正确。 React 将setIsActive 类型为Dispatch,其定义为:

type Dispatch<A> = (value: A) => void;

您的类型缺少 value 参数。这应该是正确的(另请注意,它需要是冒号而不是等号):

type Props = {
   isActive: boolean;
   setIsActive: (active: boolean) => void;
}
const Child = ({ isActive, setIsActive}: Props) {
   // rest of the component
} 

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2020-05-08
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多