如何在 React 中覆盖父 class 方法?

How to override a parent class method in React?

我正在扩展一个基础 class 并覆盖基础 class 中的一个方法。但是当我调用它时,它调用的是超级class版本。如何重写该方法?

    var Hello = React.createClass( {

        getName: function() { return "super" },

        render: function() {

            return <div>This is: {this.getName()}</div>;
        }
    });

    class HelloChild extends Hello {
        constructor(props) {
          super(props);

          console.log( this.getName());
        }
        getName()
        {
          return "Child";
        }
    };

我想让它打印 "This is: Child" 但它打印 "This is: super"

我找到了答案(改编自此处:https://gist.github.com/Zodiase/af44115098b20d69c531)- 基础 class 也需要以 ES6 方式定义:

class Hello extends React.Component {

        //abstract getName()
        getName()
        {
            if (new.target === Hello) {
                throw new TypeError("method not implemented");
            }
        }

        render() {

            return <div>This is: {this.getName()}</div>;
        }
    };

请注意,此答案提出了不同的方法:

我想知道你为什么首先要这样做,我的观点是直接耦合两个 React 组件并不是在 React 中实现可重用性的正确方法。

如果您尝试拥有多个扩展一个父组件的子组件,我会做的是拥有子组件和一个高阶组件,然后使用 Composition 实现通用功能。这样你就可以跳过那些你试图覆盖的方法,这样一切都会保持清晰。

问题是您将 ES6 类型 class 声明(例如 Hello)与老式 Javascript 声明(例如 HelloChild)混合在一起。要修复 HelloChild,请将方法绑定到 class.

class HelloChild extends Hello {
    constructor(props) {
      super(props);

      this.getName = this.getName.bind(this); // This is important

      console.log( this.getName());
    }

    getName()
    {
      return "Child";
    }
};

那就可以了

实际上你可以覆盖方法来执行子类中的代码

class Hello extends React.Component {
getName() {
 super.getName();
 }
}


class HelloChild extends Hello {
getName()
    {
      return "Child";
    }
}