简体   繁体   English

覆盖React Component方法

[英]Overriding a React Component Method

I'm using a library. 我正在使用图书馆。 This library creates a React Component, let's call it LibraryComponent. 这个库创建了一个React Component,我们称它为LibraryComponent。

I want to modify the functionality of one of this component methods, in particular handleDrag(). 我想修改此组件方法之一的功能,尤其是handleDrag()。

So I create my ExtendedLibrary module with the following code: 因此,我使用以下代码创建我的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;

As I understand changing the prototype of a creator object should change all its instances __proto__ atribute. 据我了解,更改创建者对象的原型应更改其所有实例__proto__属性。

Into my mounted LibraryComponent, If I access: 进入安装的LibraryComponent,如果我访问:

this.__proto__.handleDrag() //I'm the NEW handleDrag method.
this.handleDrag() //I'm the OLD handleDrag method.

Why? 为什么?

By contrast: 相比之下:

this.prototype.render() //I'm the NEW render method.
this.render() //I'm the NEW render method. (Accessing the __proto__ method too).

How can I do to override handleDrag definitely? 我如何做才能绝对覆盖handleDrag?

I tryied with class ExtendedLibrary extends LibraryComponent {...} too and the problem is the same (But I prefer not to include ES6 at all in my project.) 我也尝试了class ExtendedLibrary extends LibraryComponent {...} ,问题是相同的(但是我不希望在项目中完全不包括ES6。)

If you cannot/don't want to use ES6 one approach is to use composition. 如果您不能/不想使用ES6,一种方法是使用合成。 Just wrap the LibraryComponent with your own Component and use a ref to access/override a special method. 只需将LibraryComponent与您自己的Component一起包装,然后使用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/ https://jsfiddle.net/2n0x666d/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM