How to override a parent class method in React?

后端 未结 4 617
一个人的身影
一个人的身影 2021-01-05 03:07

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?

           


        
4条回答
  •  醉酒成梦
    2021-01-05 03:17

    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.

提交回复
热议问题