如何覆盖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"
答
我找到了答案(改编自此处: https://gist.github.com/Zodiase/af44115098b20d69c531 ) - 基类也需要以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>;
}
};