简体   繁体   English

如何使用 react 创建打字稿装饰器

[英]How to create a typescript decorator with react

I'm trying to create a react class decorator that adds a few props to any react component and returns the decorated component with it's current props plus the additional props from the decorator.我正在尝试创建一个反应类装饰器,该装饰器向任何反应组件添加一些道具,并返回带有当前道具的装饰组件以及来自装饰器的附加道具。

I was able to find working code for a regular typescript class decorator which can found on typescript's decorator handbook .我能够找到常规 typescript 类装饰器的工作代码,可以在 typescript 的装饰器手册中找到 However, this is for a generic class.但是,这是针对泛型类的。 It doesn't include any react types.它不包括任何反应类型。

Below is something similar that I'd like to accomplish with React and Typescript:下面是我想用 React 和 Typescript 完成的类似的事情:

 @AddOtherProps class BasicComponent extends React.Component { static defaultProps = { someProp: '' }; constructor(props) { super(props); } render() { return ( <SomeComponent someProp={this.props.someProp} // This is from current component otherProp={this.props.propFromDecorator} // This is from the decorator > {'Component Content'} </SomeComponent> ); } }

A basic decorator would function like an HoC wrapper一个基本的装饰器就像一个 HoC 包装器

function decorate(DecoratedComponent) {
  return class extends React.Component {
    render() {
      return <DecoratedComponent {...this.props} injectedProp="Hello" />;
    }
  };
}

you would use it like你会像这样使用它

@decorate
class App extends React.Component { ... }

Here's a working example.这是一个工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM