【发布时间】: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。有什么建议吗?
编辑:我想要足够通用的东西来处理所有组件类型,而不仅仅是这两种情况,这样我就可以轻松地在Fab 和ButtonWithText 以外的组件上使用 HOC。
【问题讨论】:
标签: reactjs typescript high-order-component