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

TypeScript中如何向React组件正确传递onChange等事件参数

问题原因

你编写的组件没有给入参props定义TypeScript类型,TS严格模式下会对隐式为any类型的参数抛错,同时也无法校验你传入的onChange函数的参数、返回值是否符合原生输入框事件的类型要求。

修复写法

基础写法(仅定义onChange类型)

从React导入输入框变化事件对应的内置类型,再给组件props声明类型约束即可:

import { StyledInput } from "./Input.styles";
import type { ChangeEventHandler } from "react";

// 定义组件接收的属性类型
type InputProps = {
  onChange: ChangeEventHandler<HTMLInputElement>;
};

export const Input = ({ onChange }: InputProps) => {
  return <StyledInput onChange={onChange} />;
};

这里ChangeEventHandler<HTMLInputElement>是React内置的原生input onChange事件的标准类型,和styled-components基于原生input封装的StyledInput的onChange类型完全匹配,不会再出现类型报错。

推荐写法(支持透传所有原生Input属性)

如果你的封装组件需要支持原生input的其他属性(比如value、placeholder、disabled等),不用逐个编写类型定义,直接用React内置的工具类型继承原生input的所有属性即可:

import { StyledInput } from "./Input.styles";
import type { ComponentPropsWithoutRef } from "react";

// 继承原生input标签的所有合法属性类型
type InputProps = ComponentPropsWithoutRef<"input">;

export const Input = (props: InputProps) => {
  // 直接把所有属性透传给封装的样式组件
  return <StyledInput {...props} />;
};

这种写法不需要单独绑定onChange,所有父组件传入的原生属性都会自动透传,类型校验也会自动对齐原生input的规则。

注意:不要为了临时消除报错直接给props或者onChange设置any类型,这种写法会完全丢失TypeScript的类型校验能力,后续传入不符合要求的函数时不会有任何提示,容易引发线上问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 09:09:11