【问题标题】:Write HOC as Decorator in TypeScript?在 TypeScript 中编写 HOC 作为装饰器?
【发布时间】:2019-01-07 03:00:08
【问题描述】:

我正在尝试创建一个从 React 获取参数的装饰器。上下文提供者,如果我想创建 HOC 很容易:

interface DashboardProps {
   user: User;
}

class Dashboard extends React.Component<DashboardProps> {
  render() {
     return (<span>{this.props.user.name}</span>);
  }
}

function withUser(WrappedComponent) {
  return class extends React.Component {
    render() {
      return (
        <UserContext.Consumer>
         {user => <WrappedComponent user={user} {...this.props}>}
        </UserContext.Consumer>
      );
    }
  }
}

export default withUser(Dashboard);

但我不知道如何像装饰者一样写:

@withUser
class Dashboard ...

【问题讨论】:

  • 我不建议使用装饰器。根据handbook,TypeScript 将假定修饰类具有与原始类相同的成员,这对于典型的高阶组件而言并非如此。
  • @MattMcCutchen 那么如何在 mobx 中实现 withRoute' 或 inject
  • 我不知道那个。其他人可以随意插话。

标签: reactjs typescript high-order-component


【解决方案1】:

typescript 中类装饰器的类型如下所示:

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;

这意味着类装饰器函数必须返回相同类型的组件,或者什么都不返回。

function withUser(WrappedComponent): void {
  return class extends React.Component {
    render() {
      return (
        <UserContext.Consumer>
         {user => <WrappedComponent user={user} {...this.props}>}
        </UserContext.Consumer>
      );
    }
  } as unknown as void;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 2021-01-28
    • 2011-03-19
    • 2019-10-05
    • 2018-06-08
    相关资源
    最近更新 更多