无法覆盖React中的方法 [英] Cannot Override A Method In React

查看:64
本文介绍了无法覆盖React中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个组成部分:

  var A = React.createClass({

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

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

B类扩展了A {
doSomething():任何{
console.log( I am B);
}
}

https://jsfiddle.net/wp4wshdu/



我在这里遇到同样的问题=> 如何在React中覆盖父类方法?这似乎是由于只有EC-6样式定义了组件B。我的问题是我无法更改A类。在这种情况下,如何使React使用B的方法?

解决方案

在上述 doSomething 是A上的实例方法,是B中的原型方法。





<$大致相同p $ p> 类A扩展了React.Component {
doSomething =()=> {
console.log(我是A);
}
}

B类扩展了A {
doSomething(){...}
}

doSomething 从A节拍 doSomething 来自原型链中的B。通常会在所有地方都使用ES6类中方法的原型属性,以避免此类问题。如果这不可能,那么也应该在子类中将 doSomething 用作实例方法:

  B类扩展了A {
doSomething =()=> {...}
}


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?

解决方案

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

这篇关于无法覆盖React中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆