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

ReactJS中如何通过e.target传递多个参数?

解决React onClick传递自定义参数同时获取e.target的问题

你的问题核心是调用move_box_click时没有传递事件对象e,导致函数内的e为undefined,自然无法访问e.target.id。下面是两种可行的解决方式:

方法1:箭头函数显式传递事件对象

在onClick的箭头函数中,把事件参数e作为最后一个参数传给move_box_click,和函数定义的参数顺序对应:

export const App = () => {
  const move_box_click = (x, y, boxHeight, boxWidth, e) => {
    console.log(x, y, boxHeight, boxWidth);
    console.log(e.target.id); // 现在能正常获取id
  };

  return (
    <>
      <input
        type="input"
        id="email"
        name="Email"
        value={value}
        onClick={(e) => move_box_click(100, 95, 30, 100, e)} // 显式传e
      />

      <input
        type="input"
        id="phone"
        name="Phone"
        value={value}
        onClick={(e) => move_box_click(100, 95, 30, 100, e)} // 显式传e
      />
    </>
  );
};

方法2:使用bind绑定自定义参数

利用Function.prototype.bind提前绑定自定义参数,React会自动将事件对象e作为最后一个参数传入函数,无需手动传递:

export const App = () => {
  const move_box_click = (x, y, boxHeight, boxWidth, e) => {
    console.log(x, y, boxHeight, boxWidth);
    console.log(e.target.id); // 正常获取id
  };

  return (
    <>
      <input
        type="input"
        id="email"
        name="Email"
        value={value}
        onClick={move_box_click.bind(null, 100, 95, 30, 100)} // bind绑定参数
      />

      <input
        type="input"
        id="phone"
        name="Phone"
        value={value}
        onClick={move_box_click.bind(null, 100, 95, 30, 100)} // bind绑定参数
      />
    </>
  );
};

注意点

  • 确保函数定义的参数顺序和传递顺序一致,事件对象e的位置要对应;
  • 如果使用箭头函数传递参数,每次渲染都会创建新的函数实例,若组件频繁渲染,推荐使用bind或者useCallback优化性能(针对复杂场景)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:30:38