【发布时间】:2016-05-03 14:51:15
【问题描述】:
我正在使用图书馆。这个库创建了一个 React 组件,我们称之为 LibraryComponent。
我想修改此组件方法之一的功能,特别是 handleDrag()。
所以我使用以下代码创建了我的 ExtendedLibrary 模块:
var LibraryComponent = require('libraryComponent');
LibraryComponent.prototype.handleDrag = function() {
console.log("I'm the NEW handleDrag method.");
}
LibraryComponent.prototype.render = function() {
console.log("I'm the NEW render method.");
}
module.exports = LibraryComponent;
据我了解,更改创建者对象的原型应该更改其所有实例 __proto__ 属性。
进入我安装的 LibraryComponent,如果我访问:
this.__proto__.handleDrag() //I'm the NEW handleDrag method.
this.handleDrag() //I'm the OLD handleDrag method.
为什么?
相比之下:
this.prototype.render() //I'm the NEW render method.
this.render() //I'm the NEW render method. (Accessing the __proto__ method too).
如何才能完全覆盖handleDrag?
我也尝试过class ExtendedLibrary extends LibraryComponent {...},但问题是一样的(但我不想在我的项目中包含 ES6。)
【问题讨论】:
-
LibraryComponent是如何定义的?它可能会将方法复制到实例(例如React.createClass()执行的自动绑定)。 -
如果您愿意使用 ES6 语法,您可以简单地使用类扩展 LibraryComponent。那应该可以。
标签: javascript reactjs composition