我目前正在尝试创建一个装饰器以将新方法混合到 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"
}
}
这会编译并输出预期值,但会产生编译器错误:“TestComponent”类型上不存在属性“testMethod”。有没有办法避免错误? IE。是否可以通过装饰器向 Typescript 传授有关混合到(React 组件)类中的值?
最佳答案
现在除了通过转换为 any
或定义了此方法的接口(interface)来删除类型检查外,没有其他方法可以忽略错误。
这是待处理的请求:Class Decorator Mutation
关于javascript - 使用 Typescript 时,如何创建类装饰器以将新方法混合到 React 组件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39202671/