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

如何为React输入元素的onBeforeInputCapture定义TypeScript类型?

解决React中onBeforeInputCapture事件无法访问data属性的TypeScript类型问题

问题核心在于你使用了错误的事件类型:FormEvent是通用的表单事件类型,其类型定义中并不包含data属性,而onBeforeInputCapture对应的实际事件是BeforeInputEvent(属于InputEvent的子类),所以TypeScript会提示属性不存在。

解决方案

将事件参数的类型替换为React.BeforeInputEvent<HTMLInputElement>,这是React为onBeforeInput/onBeforeInputCapture事件提供的专属合成事件类型,内置了data属性的定义:

import "./styles.css";
import { BeforeInputEvent } from 'react'

export default function App() {
  const beforeInputCaptureHandler = (event: BeforeInputEvent<HTMLInputElement>) => {
    console.log(event.data) // 此时TypeScript不会再报错
  }

  return (
    <div className="App">
      <input onBeforeInputCapture={beforeInputCaptureHandler} />
    </div>
  );
}

额外说明

如果你直接使用DOM原生的InputEvent类型也可以正常工作,但React的BeforeInputEvent是经过封装的合成事件类型,更适配React的事件冒泡/捕获机制,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:04:52