Cannot Override A Method In React

2019-07-24 12:41发布

问题:

I have two components:

var A = React.createClass( {

   doSomething: function() { return "I am A" },

    render() {
    return(
        <h1>{this.doSomething()}</h1>
      );    
   }
    });

class B extends A {
   doSomething(): any {
     console.log("I am B");
   } 
}

https://jsfiddle.net/wp4wshdu/

I have the same problem as here => How to override a parent class method in React? And it seems to be due to the fact that only component B defined in the EC-6 style. My problem is that I cannot change A class. How can I make React use the B's method in this case?

回答1:

In the code above doSomething is instance method on A and prototype method in B.

It's roughly same as

 class A extends React.Component {
   doSomething = () => {
     console.log("I am A");
   } 
 }

 class B extends A {
   doSomething() { ... } 
 }

And doSomething from A beats doSomething from B in prototype chain. It's conventional to stick to prototype properties for methods in ES6 classes everywhere to avoid problems like this one. If this is not possible, doSomething should be made an instance method in child class, too:

 class B extends A {
   doSomething = () => { ... } 
 }