如何覆盖React中的父类方法?

Don*_*mmy 7 javascript ecmascript-6 reactjs react-jsx

我正在扩展基类并覆盖基类中的方法.但是当我调用它时,它会调用超类版本.如何覆盖该方法?

    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";
        }
    };
Run Code Online (Sandbox Code Playgroud)

我希望它打印"这是:孩子",但它打印"这是:超级"

Rya*_*ton 5

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

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

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

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

    getName()
    {
      return "Child";
    }
};
Run Code Online (Sandbox Code Playgroud)

然后就可以了。


Don*_*mmy 3

我找到了答案(改编自这里: https: //gist.github.com/Zodiase/af44115098b20d69c531) - 基类也需要以 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>;
        }
    };
Run Code Online (Sandbox Code Playgroud)

  • 这就是OP^ (11认同)