How to override a parent class method in React?

别来无恙 提交于 2019-12-19 02:32:09

问题


I'm extending a base class and overriding a method in the base class. But when I call it, it calls the super class version. How do I override the method?

    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";
        }
    };

I want it to print "This is: Child" but it prints "This is: super"


回答1:


I found the answer (adapted from here: https://gist.github.com/Zodiase/af44115098b20d69c531 ) - the base class needs to also be defined in an ES6 manner:

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>;
        }
    };



回答2:


The problem is that you're mixing ES6 type class declaration (ex. Hello) with old school Javascript declaration (ex. HelloChild). To fix HelloChild, bind the method to the 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";
    }
};

Then it'll work.




回答3:


Actually you can override method to execute code from your subclass

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


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



回答4:


Please note that this answer proposes different approach:

I wonder why you should do this in the first place, my point is that directly coupling two react components is not a right way to implement re-usability in React.

If you are trying to have multiple child components which extends one parent, What I would do is, to have child components and a higher-order component and then implement common functionality with Composition. This way you can skip those methods, which you were trying to override and so everything would stay clear.



来源:https://stackoverflow.com/questions/38758518/how-to-override-a-parent-class-method-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!