【问题标题】:How do I declare a generic React component in a const variable from a higher-order component?如何在高阶组件的 const 变量中声明通用 React 组件?
【发布时间】:2018-10-10 13:30:03
【问题描述】:

我有如下 TypeScript 代码:

interface Props<T> {}

function HOC<P>(component: React.ComponentType<P>): React.ComponentType<P> {
  return component;
}

const MyClass = HOC(class MyClass<T> extends React.Component<Props<T>, {}> {});
type MyClass<T> = React.ComponentType<Props<T>>;

function render() {
  return <MyClass<string> />;
}

但这不起作用,因为我在MyClass&lt;string&gt; 一行收到以下错误:

[ts]
JSX element type 'ReactElement<any> | null' is not a constructor function for JSX elements.
  Type 'null' is not assignable to type 'ElementClass'.
[ts] Expected 0 type arguments, but got 1.

如果我删除 HOC 和类型声明,它编译得很好:

interface Props<T> {}

class MyClass<T> extends React.Component<Props<T>, {}> {};

function render() {
  return <MyClass<string> />;
}

所以我的问题是,假设我无法修改HOC 的类型声明,我该如何声明const MyClass(必要时使用type MyClass&lt;T&gt;)以便第一个示例编译成功?

【问题讨论】:

  • 如果您不喜欢编写可能会随着代码更改和隐藏问题而过时的类型断言,请参阅this answer 了解另一种方法。

标签: reactjs typescript jsx


【解决方案1】:

既然MyClass 是一个泛型构造函数,您将需要使用类型断言来让 typescript 编译器:

interface Props<T> {
  prop: T
}

function HOC<P>(component: React.ComponentType<P>): React.ComponentType<P> {
  return component;
}

const MyClass = HOC(class MyClass<T> extends React.Component<Props<T>, {}> {}) as {
  new <T>(props: Props<T>, context?: any): React.Component<Props<T>> // Generic constructor
}

function render() {
  return <MyClass<string> prop="" />;
}

function render2() {
  return <MyClass<number> prop={1} />;
}

注意据我所知,typescript 缺乏对您正在寻找的泛型类型转换进行建模的能力,即使您可以更改 HOC。

【讨论】:

    猜你喜欢
    • 2022-09-22
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多