I'm attempting to subclass a React component, and my overridden methods aren't being called:
class Foo extends React.Component {
someMethod() { ... }
render() {
return <div>{this.someMethod()}</div>;
}
}
class Bar extends Foo {
someMethod() {
// Never gets called
}
}
In fact, when I render a <Bar />
in my DOM and look at the component in the debugger, it shows the component type as 'Foo'.
(Also, please note that I'm familiar with all of the arguments about composition vs. inheritance. Trust me, inheritance really is the right answer for my specific use case, so let's not start that argument.)
(Also, I know about potential duplicate issue #27233491, but the solutions given there don't actually seem to work for me.)
Update:
I see @Aaron's example on CodePen showing how this works, but I'm seeing different behavior in my app. Specifically:
class Foo extends React.Component {
render() {
console.log(this); // Always prints 'Foo...'.
return <div></div>
}
}
class Bar extends Foo {
render() {
console.log(this); // Always prints 'Bar...'.
return super.render();
}
}
What I see on the dev console when I render Bar is:
> Bar { props: ...etc. }
> Foo { props: ...etc. }
In other words, the first logging statement prints 'this' as being of type Bar, and the second one prints 'this' as being type Foo. Both from the same render() call.
Found the problem: I was using withRouter() on the base class. You can't inherit from a HoC, it treats all of the methods as though .bind(this) had been called on them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With