2016-05-03 64 views
1

我正在使用库。这个库创建一个React Component,我们称它为LibraryComponent。覆盖React组件方法

我想修改其中一个组件方法的功能,特别是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?

我tryied与class ExtendedLibrary extends LibraryComponent {...}过,问题是相同的(但我更喜欢不包括ES6都在我的项目。)

+0

如何'LibraryComponent'定义?它可能会将该方法复制到实例(例如,由'React.createClass()'执行的自动绑定)。 – JMM

+0

如果您打算使用ES6语法,您可以简单地使用一个类来扩展LibraryComponent。这应该工作。 –

回答

2

如果你不能/不想使用ES6一个方法是使用组成。只需用自己的Component包装LibraryComponent并使用ref来访问/覆盖特殊的方法。

var Wrapper = React.createClass({ 
    libLoaded: function(libComponent) { 
    if (libComponent) { 
     libComponent.onDrag = this.onDrag; 
    } 
    }, 
    onDrag: function() { 
    return "Hello drag"; 
    }, 
    render: function() { 
    return <LibraryComponent ref={this.libLoaded}/>; 
    } 
}); 
ReactDOM.render(
    <Wrapper/>, 
    document.getElementById('container') 
); 

https://jsfiddle.net/2n0x666d/3/