【问题标题】:React typescript how to type a hoc反应打字稿如何键入一个 hoc
【发布时间】:2019-07-10 14:02:09
【问题描述】:

我想在我的全新项目中使用打字稿 但是我很难输入 HOC 组件

const withClass = (Wrapped: Component<any, {}, any>, className: string) => {
  return props => (
    <div className={className}>
      <Wrapped />
    </div>
  );
};

它不适用于此错误

类型错误:“typeof App”类型的参数不可分配给“组件”类型的参数。 “typeof App”类型缺少“Component”类型的以下属性:context、setState、forceUpdate、render 和另外 3 个。 TS2345

那么正确的方法是什么?

【问题讨论】:

  • 你的App类是继承自Component吗?
  • 是的,它继承自Component

标签: reactjs typescript


【解决方案1】:

Component&lt;...&gt; 类型指定React.Component 的一个实例。

如果意图是提供组件本身并且不将 HOC 限制为类组件,那么正确的类型是 ComponentType

const withClass = (Wrapped: React.ComponentType<any>, className: string) => { ... }

最好使用特定的道具类型而不是any。如果应该像 HOC 所期望的那样将 props 传递给包装的组件,那么 this issue 也应该被解决:

const withClass = <P extends {}>(Wrapped: React.ComponentType<P>, className: string) => {
  return props => (
    <div className={className}>
      <Wrapped {...props as P} />
    </div>
  );
};

【讨论】:

  • 感谢您的聪明回复,但在 ts 方面还很新,您能解释一下函数之前的语法

    吗?

  • 这是通用参数,typescriptlang.org/docs/handbook/generics.html。当没有像 withClass(SomeComponent) 这样在调用时指定时,将推断 Wrapped 的道具。这是通常处理道具的方式。见github.com/piotrwitek/react-redux-typescript-guide
  • 我收到一条错误消息,提示 props 隐含为“任何”。我该如何解决?
  • 忽略我的最后一条评论:我将 props 更改为 (props: P) 并且有效
猜你喜欢
  • 2019-12-16
  • 2021-10-04
  • 2017-09-02
  • 2019-07-11
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 2021-06-14
  • 2023-02-14
相关资源
最近更新 更多