How to add multiple event handlers to same event in React.js

后端 未结 4 1038
星月不相逢
星月不相逢 2021-02-13 19:35

All:

I wonder if it is possible that binding multiple event handlers to same event?

For example:

var LikeToggleButton = React.createClass({
    r         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-02-13 20:25

    For an extensible way that does't require the component to know about components that use it - save the onClick event before changing it. This is highlights extracted from the actual working code:

    button.jsx

    class Button extends React.Component {
    
      constructor(props) {
        super(props);
        this.state= { callback: false};
      }
    
      click(){
        //do stuff here
        if(this.state.callback) { this.state.callback.call(); }
      }
    
      render () {
        this.state.callback = this.props.onClick; // save the onClick of previous handler
    
        return (
          
        );
      }
    }
    export default Button;
    

    Then in another component you can use the button and it can have it's own onClick handler:

    class ItemButtons extends React.Component {
      itemClick () {
        //do something here;
      }
    
    render () {
        const buttons = [
          (
              
          )
        ];
    
        return (
    { buttons }
    ); } export default ItemButtons;

提交回复
热议问题