Cannot Override A Method In React

最后都变了- 提交于 2019-12-13 00:20:13

问题


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 = () => { ... } 
 }


来源:https://stackoverflow.com/questions/45443416/cannot-override-a-method-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!