我扩展基类并覆盖基类中的方法。但是当我调用它时,它会调用超类版本。如何覆盖该方法?
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";
}
};
我想要打印&#34;这是:儿童&#34;但它打印&#34;这是:超级&#34;
答案 0 :(得分:2)
我找到了答案(改编自此处:https://gist.github.com/Zodiase/af44115098b20d69c531) - 基类也需要以ES6方式定义:
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>;
}
};
答案 1 :(得分:2)
实际上,您可以覆盖从子类
执行代码的方法class Hello extends React.Component {
getName() {
super.getName();
}
}
class HelloChild extends Hello {
getName()
{
return "Child";
}
}
答案 2 :(得分:1)
请注意,这个答案提出了不同的方法:
我想知道为什么你应该首先这样做,我的观点是直接耦合两个反应组件并不是在React中实现可重用性的正确方法。
如果您尝试使用多个子组件来扩展一个父组件,我将要做的是拥有子组件和更高阶组件,然后使用Composition实现常用功能。这样你就可以跳过那些你试图覆盖的方法,这样一切都会保持清晰。
答案 3 :(得分:1)
问题在于你将ES6类型类声明(例如Hello)与旧学校Javascript声明(例如HelloChild)混合在一起。要修复HelloChild,请将方法绑定到类。
class HelloChild extends Hello {
constructor(props) {
super(props);
this.getName = this.getName.bind(this); // This is important
console.log( this.getName());
}
getName()
{
return "Child";
}
};
然后它会起作用。