【问题标题】:How to add a prop to super React component in TypeScript?如何在 TypeScript 中为超级 React 组件添加道具?
【发布时间】:2019-10-18 08:00:36
【问题描述】:

我将编写一个类似 HOC 的函数来为 React 组件添加一个“可见”的道具。当 visible 属性设置为 false 时,render 函数只是 return null,必须保持状态。

我写了一个 JavaScript 版本,但仍然无法在 TypeScript 中重写它,因为我找不到向超级 React 组件添加 prop 的方法。

按照我的尝试:

import React from "react";

interface IVisibleProps {
  /** @default true */
  visible?: boolean;
}

const withVisible = <P>(Component: React.ComponentClass<P>): React.ComponentClass<P & IVisibleProps> => (
  class VisibleComponent extends Component {
    public static defaultProps = { visible: true, ...Component.defaultProps };
    public static displayName = Component.displayName || Component.name;

    public render() {
      return this.props.visible ? super.render() : null;
    }
  }
);

export default withVisible;

我仍然找不到通过打字检查的方法。特别是如何将IVisibleProps添加到返回组件的通用P中。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    有点奇怪的修复:

    function withVisible<P>(
      Component: React.ComponentClass<P>
    ): ComponentClass<P & IVisibleProps> {
      return class VisibleComponent extends Component {
        public static defaultProps: Partial<P & IVisibleProps> = {
          visible: true,
          ...Component.defaultProps!
        };
        public static displayName = Component.displayName || Component.name;
        public readonly props!: Readonly<P & IVisibleProps>;
        public render() {
          return this.props.visible ? super.render() : null;
        }
      };
    
    

    public readonly props!: Readonly&lt;P &amp; IVisibleProps&gt;; 让我们扩展 props。

    ...Component.defaultProps! 实际上是一个肮脏的 hack:defaultProps 可以未定义,在这种情况下,{...Component.defaultProps} 有一个空的{} 签名,而不是接口所需的套件Partial&lt;P&gt;。这就是为什么它不起作用的原因,但它只是打字不好,没有什么可担心的,所以我们可以绕过检查 !

    【讨论】:

    • 您的意思是class VisibleComponent extends Component 哪个Component 是参数?
    • @Gerhut,是的,很抱歉这个错误
    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 2017-06-12
    • 2020-10-19
    • 2021-12-24
    • 2018-08-22
    • 2021-06-30
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多