当使用Typescript时,如何创建一个类装饰器来将新方法混合到React组件中?

How do I create a class decorator for mixing new methods into a React component when using Typescript?

本文关键字:新方法 组件 React 混合 Typescript 何创建 创建 一个      更新时间:2023-09-26

我目前正在尝试创建一个装饰器来将新方法混合到React组件中。我通过下面的命令得到了想要的结果:

function testDecorator(target) {
  const testMethod = function testMethod() {
    return 'successfully mixed testMethod into component';
  };
  target.prototype.testMethod = testMethod;
}
@testDecorator
export class TestComponent extends React.Component<{}, {}> {
// ...
  render() {
    console.log('this.testMethod', this.testMethod());
    // outputs "successfully mixed testMethod into component"
  }
}

这会编译并输出预期的值,但是会产生一个转译器错误:属性'testMethod'在类型'TestComponent'上不存在。有没有办法避免这个错误?也就是说,是否有可能通过装饰器教Typescript关于混合到(React组件)类中的值?

现在没有办法忽略这个错误,除了通过强制转换到any或定义了这个方法的接口来删除类型检查。

Class Decorator Mutation

多亏@Amid指向挂起的类装饰器突变Typescript请求的链接,我发现如果没有额外的样板文件,就没有办法做到这一点。因此,我选择了一个解决方案,其中I:

  1. 让装饰器包装的任何类也实现一个接口,为装饰器添加的所有属性提供类型;和
  2. 为类本身中添加的函数提供替代,以满足编译器。
例如:

const testDecorator = (target: Function) => {
  const testMethod = () => 'successfully mixed testMethod into component';
  target.prototype.testMethod = testMethod;
};
interface TestDecorated {
  testMethod: () => any;
}
@testDecorator
export class TestClass extends React.Component<{}, {}> implements TestDecorated {
  //...       
  testMethod;
  render() {
    console.log('this.testMethod', this.testMethod());
    // outputs: "successfully mixed testMethod into component"
  }
}

也许你可以使用这些lib?!或者至少可以了解如何实现装饰器:

核心decorator