How to override a parent class method in React?
11,851
Solution 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>;
}
};
Solution 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.
Solution 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";
}
}
Comments
-
Don Rhummy almost 2 years
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"
-
Andrew Li almost 8 yearsThe OP wants to know how to access subclass from superclass (which is impossible AFAIK), not how to make an abstract method-the super and subclass methods have different implementations
-
Saad almost 8 yearsThat is the OP ^