You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js中如何在JSX的onClick事件中传递参数

React JSX中onClick事件传递参数的实现方法

下面是针对你的需求提供的两种常用实现方案,可根据实际场景选择:

方案1:箭头函数包裹(最通用,适合绝大多数场景)

直接在onClick绑定位置用箭头函数包裹目标方法,调用时传入你需要的参数即可,改造后的代码如下:

// 改造handleClick接收自定义参数
function handleClick(targetPath) {
  history.push(targetPath);
}

.....

<Button 
  color="primary" 
  size="small"
  // 箭头函数包裹调用,传入自定义参数
  onClick={() => handleClick("/home")}
  className={classes.notificationbutton}>
     View
</Button>

注意:该方式每次组件渲染都会生成新的箭头函数实例,普通业务场景下性能损耗可完全忽略,仅在超大量列表渲染场景下可选用方案2优化

方案2:函数柯里化(适合性能优化、重复调用场景)

将handleClick改造成返回函数的柯里化形式,避免重复生成匿名函数:

// 柯里化改造:先接收参数,返回实际触发的事件处理函数
function handleClick(targetPath) {
  return () => {
    history.push(targetPath);
  }
}

.....

<Button 
  color="primary" 
  size="small"
  onClick={handleClick("/home")}
  className={classes.notificationbutton}>
     View
</Button>

附加场景:同时获取事件对象和自定义参数

如果需要用到事件本身的属性(比如阻止默认行为、获取元素属性),两种方案的写法调整如下:

  • 箭头函数版本:
function handleClick(targetPath, e) {
  e.preventDefault();
  history.push(targetPath);
}

// 调用时将事件对象e透传
onClick={(e) => handleClick("/home", e)}
  • 柯里化版本:
function handleClick(targetPath) {
  return (e) => {
    e.preventDefault();
    history.push(targetPath);
  }
}

// 调用方式不变,事件对象会自动传入返回的处理函数
onClick={handleClick("/home")}

内容的提问来源于stack exchange,提问作者user15404864

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:24:01