【问题标题】:How do I make a higher order React component with Typescript?如何使用 Typescript 制作更高阶的 React 组件?
【发布时间】:2021-08-15 06:40:43
【问题描述】:

我正在尝试使用 Typescript 制作更高阶的组件,但我遇到了类型不匹配的问题。我完全剥离了它,所以它应该只包装组件,但仍然出现错误:

import * as React from 'react';

export function createPage<Props extends {}, ComponentType extends React.ComponentType<Props>>(
  Component: ComponentType
) {
  return class WrappedComponent extends React.Component<Props> {
    render() {
      return <Component {...this.props}></Component>;
    }
  }
}

我得到的错误是:

Type 'Readonly & Readonly' 不可分配给类型 'IntrinsicAttributes & LibraryManagedAttributes'。

看起来IntrinsicAttributes 什么都比不上,但LibraryManagedAttributes 对我来说绝对是不可思议的。

【问题讨论】:

    标签: reactjs typescript higher-order-components


    【解决方案1】:

    您只需要为 Props 提供一个通用参数

    export function createPage<Props>(
      Component: React.ComponentType<Props>
    ) {
      return class WrappedComponent extends React.Component<Props> {
        render() {
          return <Component {...this.props}></Component>;
        }
      }
    }
    

    Playground

    【讨论】:

    • 谢谢,就这样!你能解释一下为什么会这样吗?
    猜你喜欢
    • 2017-09-26
    • 1970-01-01
    • 2019-07-25
    • 2020-08-31
    • 2019-04-30
    • 2018-05-23
    • 2019-10-25
    • 2020-02-06
    • 2018-04-07
    相关资源
    最近更新 更多