简体   繁体   English

将事件和参数都传递给React中的处理程序

[英]Passing both the event and an argument to a handler in React

In React I have created a button, like this: 在React中,我创建了一个按钮,如下所示:

<Link size="button" onClick={this._handleShareClick.bind(this, this.props.shareID)} href={this.props.URL}>{shareText}</Link>

What I want to do is pass the share ID, but also have access to the regular event object, to allow me to use e.preventDefault(); 我想做的是传递共享ID,但也可以访问常规事件对象,以允许我使用e.preventDefault();

When I pass to the handler: 当我传递给处理程序时:

_handleShareClick = (e, shareID) => {
    console.log(shareID);
    e.preventDefault();
}

The shareID doesn't console log, and I also get the following error in my console: shareID没有控制台日志,我的控制台中也出现以下错误:

Uncaught TypeError: Cannot read property 'preventDefault' of undefined

Is there a reason I can't access both of these things, or is there another approach that I am missing? 是因为我无法同时访问这两种东西,还是我缺少另一种方法?

您应该使用:

onClick={(e) => (e.preventDefault(), this._handleShareClick(this.props.shareID))

If u need to pass custom parameters, then u can simply pass the parameters to the bind call. 如果您需要传递自定义参数,则只需将参数传递给绑定调用即可。 The SyntheticEvent will be passed as the second parameter to the handler. SyntheticEvent将作为第二个参数传递给处理程序。

handleClick(param, e) {
  console.log('Parameter', param);
  console.log('Event', e);
}

render() {
  <button onClick={this.handleClick.bind(this, 'Parameter')}></button>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM