2017-08-09 79 views
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)" /> 
    } 
} 

我如何能确保在FooFoo.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很陌生,假设我忽略了一些明显的东西。由于

+0

FancyFoo类是什么样的? – MatTheWhale

回答

1

我解决了这个通过利用传播对象解构在Foo.render方法:

render() { 

    // extract FancyFoo's onClick handler 
    const {onClick, ...props} = this.props; 

    // pass only remaining props to Bar constructor, override onClick 
    return (
     <Bar 
      onClick={this.doSomething} 
      {...props} /> 
    ); 
} 

...如预期那么Foo的doSomething作品:

doSomething() { 
    // do the default thing 
    // ... 

    // this.props. onClick references FancyFoo's implementation 
    'function' === typeof this.props.onClick && this.props.onChange.apply(this, arguments); 
} 

现在Foo.doSomething执行紧接着FancyFoo.doSomething