当使用Typescript时,如何创建一个类装饰器来将新方法混合到React组件中?
How do I create a class decorator for mixing new methods into a React component when using Typescript?
我目前正在尝试创建一个装饰器来将新方法混合到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
或定义了这个方法的接口来删除类型检查。
多亏@Amid指向挂起的类装饰器突变Typescript请求的链接,我发现如果没有额外的样板文件,就没有办法做到这一点。因此,我选择了一个解决方案,其中I:
- 让装饰器包装的任何类也实现一个接口,为装饰器添加的所有属性提供类型;和
- 为类本身中添加的函数提供替代,以满足编译器。
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相关文章:
- 向对象添加新方法和值,同时避免重复
- 追加新web组件时出现线程问题
- 什么'在javascript中将新方法添加到对象中的区别是什么
- 在原型上声明新方法
- 编写 if 语句的新方法
- 使用原型将新方法添加到JScrollPane
- 如何在响应和请求中添加新方法
- ES5提供的新方法的实际用途是什么?
- 在javascript中的新方法中使用构造函数中的privat-var
- 如何通过原型添加Nodelist/HtmlColaction新方法
- 在jQuery中使用带有上下文节点的子选择器的新方法是什么?
- 在递归聚合物组件中插入新子组件时,无法读取未定义的属性“concat”
- Typescript装饰类添加新方法
- 新Ember组件中输入助手的最佳实践
- 如何在JavaScript中为字符串添加新方法?
- 在javascript中创建原型,添加一个新方法来引导日期拾取器
- 如何在javascript中为根类对象添加一个新方法
- Rails 3.1:使用'respond_to .的新方法format.js& # 39;没有'page
- 当使用Typescript时,如何创建一个类装饰器来将新方法混合到React组件中?
- 创建一个新方法,查找数组中连续条目的最大和