本文介绍了如何覆盖React中的父类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在扩展基类并覆盖基类中的方法。但是当我调用它时,它会调用超类版本。如何覆盖方法?
I'm extending a base class and overriding a method in the base class. But when I call it, it calls the super class version. How do I override the method?
var Hello = React.createClass( {
getName: function() { return "super" },
render: function() {
return <div>This is: {this.getName()}</div>;
}
});
class HelloChild extends Hello {
constructor(props) {
super(props);
console.log( this.getName());
}
getName()
{
return "Child";
}
};
我希望它打印This is:Child,但它打印出This is:super
I want it to print "This is: Child" but it prints "This is: super"
推荐答案
我找到了答案(改编自此处:) - 基类也需要以ES6方式定义:
I found the answer (adapted from here: https://gist.github.com/Zodiase/af44115098b20d69c531 ) - the base class needs to also be defined in an ES6 manner:
class Hello extends React.Component {
//abstract getName()
getName()
{
if (new.target === Hello) {
throw new TypeError("method not implemented");
}
}
render() {
return <div>This is: {this.getName()}</div>;
}
};
这篇关于如何覆盖React中的父类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!