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

React+TypeScript中点击事件如何获取子元素?

React + TypeScript 点击事件中获取子元素的解决方法

问题核心是e.target的指向问题:当你点击<div>内部的<input>或<label>时,e.target会变成被点击的子元素,而非绑定onClick的父<div>,导致firstElementChild调用失效。

正确实现方式

使用e.currentTarget替代e.target——它始终指向绑定事件处理函数的元素(即这里的<div>),且TypeScript会根据你定义的MouseEvent<HTMLDivElement>正确推断其类型,安全访问子元素属性。

修改后的代码:

import { MouseEvent } from "react";

const clicked = (e: MouseEvent<HTMLDivElement>) => {
  console.log(e.currentTarget); // 固定指向绑定onClick的div
  console.log(e.currentTarget.firstElementChild); // 正常获取第一个子元素(input)
}

const QuizQuestionContainer = () => {
  // 假设checkOption、checked、option1为已定义变量
  return(
    <form>
      <div onClick={clicked}>
        <input
          type="radio"
          value={option1}
          name="option"
          onChange={checkOption}
          checked={checked === option1}
        />
        <label>{option1}</label>
      </div>
    </form>
  )
}

export default QuizQuestionContainer;

额外优化建议

如果需要精准获取特定子元素(避免依赖子元素顺序),可以使用querySelector:

// 获取div内的input元素
const inputElement = e.currentTarget.querySelector('input') as HTMLInputElement;
// 获取div内的label元素
const labelElement = e.currentTarget.querySelector('label') as HTMLLabelElement;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:15:35