3

我正在尝试创建一个反应类装饰器,它向任何反应组件添加一些道具,并返回带有当前道具的装饰组件以及来自装饰器的附加道具。

我能够在 typescript's decorator handbook上找到常规 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>
    );
  }
}

4

1 回答 1

0

一个基本的装饰器会像一个 HoC 包装器一样工作

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

你会像这样使用它

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

这是一个工作示例。

于 2018-08-29T19:08:00.040 回答