1
我试图扩展组件的“子类化”组件的默认事件处理程序功能。在React中扩展组件事件处理程序道具
如果我有一个简单的组件是这样的:
export class Foo extends React.Component {
doSomething() {
// I want to do this first...
}
render() {
return <Bar onClick="() => this.doSomething.bind(this)" />
}
}
...和我试图通过组成以扩展:
export class FancyFoo extends React.Component {
doSomethingFancy() {
// ...and do this second
}
render() {
return <Foo onClick="() => this.doSomethingFancy.bind(this)" />
}
}
我如何能确保在Foo
那Foo.doSomething
是在SuperFoo.doSomethingFancy
之前立即执行?我想这样的做法:
export class Foo extends React.Component {
constructor(props) {
super(props);
this.doSomething = this.doSomething.bind(this);
}
doSomething() {
// do the default thing
console.log('here!'); // <-- never happens
// if "subclass" provided a callback, call it next
'function' === typeof this.props.onClick && this.props.onChange.apply(this, arguments);
}
render() {
return (
<Bar
onClick={this.doSomething}
{...this.props} />
);
}
}
...但Foo.doSomething
不会被调用,而SuperFoo.doSomethingFancy
是。我对React很陌生,假设我忽略了一些明显的东西。由于
FancyFoo类是什么样的? – MatTheWhale