【问题标题】:Add property to React Typescript High Order Component including implementation向 React Typescript 高阶组件添加属性,包括实现
【发布时间】:2020-05-30 19:35:14
【问题描述】:

我正在尝试构建一个我想要执行以下操作的 React HOC:

  • 获取传入的组件,添加(或覆盖)hidden 属性,并返回修改后的组件
  • 渲染组件,以便当“隐藏”为真时,不渲染任何内容

我在 Typescript 中为特定组件工作,如下所示

import React from 'react';
import { FabProps, Fab } from '@material-ui/core';
import ButtonWithText, { ButtonWithTextProps } from '../UserInterface/ButtonWithText';

interface IFabWithHiddenProps {
    hidden?: boolean;
}

export class ButtonWithTextWithHidden extends React.Component<ButtonWithTextProps & IFabWithHiddenProps> {
    render(){
        const {
            hidden,
            ...buttonProps
        } = this.props;

        if (hidden === undefined || hidden) {
            return <></>;
        }
        else {
            return <ButtonWithText {...buttonProps} />;
        }
    }
}

export class FabWithHidden extends React.Component<FabProps & IFabWithHiddenProps> {
    render(){
        const {
            hidden,
            ...buttonProps
        } = this.props;

        if (hidden === undefined || hidden) {
            return <></>;
        }
        else {
            return <Fab {...buttonProps} />;
        }
    }
}

但是,我想将这两个类变成一个 HOC。有什么建议吗?

编辑:我想要足够通用的东西来处理所有组件类型,而不仅仅是这两种情况,这样我就可以轻松地在FabButtonWithText 以外的组件上使用 HOC。

【问题讨论】:

    标签: reactjs typescript high-order-component


    【解决方案1】:

    我认为你需要合并你的两个接口并像这样处理你的问题:

    interface IFabWithHiddenProps extends ButtonWithTextProps , FabProps  {
      hidden?:boolean;
      type : string; // this can be fab | button
    }
    
    

    并像这样使用它:

    export default class FabOrButtonWithHidden extends React.Component<IFabWithHiddenProps> {
        render(){
            const {
                hidden,
                type
                ...rest
            } = this.props;
    
            if (hidden === undefined || hidden) {
                return <></>;
            } else if(type === "button") {
               return (
                <ButtonWithText {...rest} />
               )
    
            }
            else {
                return <Fab {...rest} />;
            }
        }
    }
    
    

    【讨论】:

    • 有没有办法进一步抽象它,使其适用于所有组件类型?我想要适用于所有组件类型的东西,这样我就不必在每次需要处理新组件时都进行更改。
    • 只需添加更多 types 或从更多 prop type 扩展到它,它会按照您的意愿正常工作
    • 我肯定想要一种更抽象的方法,使用模板,或者也许有更好的方法。另一个问题是,当扩展多个类时,某些类型存在于一个类中但不存在于另一个类中,...rest 可能会在组件没有另一个所需的属性的情况下产生错误(尽管我没有测试那)
    猜你喜欢
    • 2019-10-25
    • 1970-01-01
    • 2019-07-25
    • 2018-09-17
    • 2017-09-26
    • 2021-06-02
    • 1970-01-01
    • 2021-12-05
    • 2019-08-20
    相关资源
    最近更新 更多