React onClick - pass event with parameter

后端 未结 5 709
半阙折子戏
半阙折子戏 2020-12-22 17:33

Without Parameter

function clickMe(e){
  //e is the event
}


With Para

5条回答
  •  醉酒成梦
    2020-12-22 17:59

    Currying with ES6 example:

    const clickHandler = param => event => {
      console.log(param); // your parameter
      console.log(event.type); // event type, e.g.: click, etc.
    };
    

    Our button, that toggles handler:

    
    

    If you want to call this function expression without an event object, then you'd call it this way:

    clickHandler(1)();

    Also, since react uses synthetic events (a wrapper for native events), there's an event pooling thing, which means, if you want to use your event object asynchronously, then you'd have to use event.persist():

    const clickHandler = param => event => {
      event.persist();
      console.log(event.target);
      setTimeout(() => console.log(event.target), 1000); // won't be null, otherwise if you haven't used event.persist() it would be null.
    };
    

    Here's live example: https://codesandbox.io/s/compassionate-joliot-4eblc?fontsize=14&hidenavigation=1&theme=dark

提交回复
热议问题