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

是否可以将id、字符串或组件key传递给onFocus事件?

实现方案

可以将key、ID这类自定义标识传递给onFocus的处理逻辑,你只需要调整事件处理函数的参数定义和调用方式即可,具体修改如下:

第一步:调整handleFocus参数定义与实现

原handleFocus只接收事件对象,修改为支持同时接收事件对象和自定义key/ID,兼容原生触发和手动调用两种场景:

// 类型定义调整
handleFocus: (e: SyntheticEvent<FormInputElements>, customKey?: string) => void,

// 函数实现调整
const handleFocus = (e: SyntheticEvent<FormInputElements>, customKey?: string) => {
  setHasFocus(true);
  handleEvent(onFocus, e.currentTarget.value);
  
  // 拿到传入的customKey后可执行聚焦逻辑
  if (customKey) {
    // 提前给输入组件绑定data-key属性,这里通过key找到对应元素触发聚焦
    const targetInput = document.querySelector(`[data-key="${customKey}"]`) as HTMLInputElement;
    targetInput?.focus();
  }
};

第二步:给渲染的输入组件绑定自定义属性与参数

渲染输入元素时,把组件的key绑定到自定义data-key属性上,同时给onFocus事件提前绑定当前组件的key:

<input
  key={component.key}
  data-key={component.key} // 自定义属性存key,方便DOM查询
  onChange={handleChange}
  onFocus={(e) => handleFocus(e, component.key)} // 原生触发时自动传入key
  // 其余原有属性保持不变
/>

第三步:修改handleChange中的手动调用逻辑

在handleChange的判断分支中手动调用handleFocus时,传入当前事件对象和组件key即可:

const handleChange = (e: SyntheticEvent<FormInputElements>) => {
  handleEvent(onChange, e.currentTarget.value);

  if (hasFocus && showErrors) {
    setResolvedErrors(true);
    // 传入事件对象和当前组件的key
    handleFocus(e, component.key);
  }
};

注意事项

  • React的key是框架内部保留属性,无法通过DOM节点直接获取,因此必须自行绑定到data-key这类自定义属性上才能用于元素查询
  • 如果不需要保留原有事件对象的所有属性,也可以构造最小模拟事件对象传入,满足类型校验要求即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:54:06