【问题标题】:Overriding a React Component Method覆盖 React 组件方法
【发布时间】: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


【解决方案1】:

如果你不能/不想使用 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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 2019-05-06
    • 2018-01-08
    • 1970-01-01
    • 2022-12-04
    • 2022-06-18
    相关资源
    最近更新 更多