How to use inheritance with React components and es6 classes

I am trying to subclass a React component and my overridden methods are not 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 draw <Bar /> in my DOM and look at the component in the debugger, it shows the component type as "Foo".

(Also note that I am familiar with all the arguments about composition and inheritance. Believe me, inheritance is indeed the right answer for my particular use case, so don't start this argument.)

(In addition, I know about potential duplicate release # 27233491 , but the solutions offered there actually don't work for me.)

Update:

I see an @Aaron example in CodePen showing how this works, but I see different behavior in my application. In particular:

 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 rendering Bar:

 > Bar { props: ...etc. } > Foo { props: ...etc. } 

In other words, the first logger prints 'this' as a string of type Bar, and the second prints 'this' as a type of Foo. Like from a single render () call.

+5
source share
1 answer

Found a problem: I used withRouter () in the base class. You cannot inherit from HoC, it considers all methods as if .bind (this) was called on them.

+3
source

All Articles