我正在扩展一个基类并覆盖基类中的一个方法。但是当我调用它时,它调用的是父类(super class)版本。如何覆盖该方法?
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”
最佳答案
问题是您将 ES6 类型类声明(例如 Hello)与老式 Javascript 声明(例如 HelloChild)混合在一起。要修复 HelloChild,请将方法绑定(bind)到类。
class HelloChild extends Hello {
constructor(props) {
super(props);
this.getName = this.getName.bind(this); // This is important
console.log( this.getName());
}
getName()
{
return "Child";
}
};
然后它会起作用。
关于javascript - 如何在 React 中重写父类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38758518/