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

React+TypeScript父组件向子组件传函数时类型不匹配如何解决

报错原因

这个报错是因为你的<Dogs />子组件没有声明接收onDogSelected属性的TypeScript类型,TS默认只能识别React组件内置的key、ref、children属性,无法识别你自定义的props,所以会提示属性不存在。

解决步骤

  1. 首先在<Dogs />组件的定义文件中,声明组件的Props类型:
// 可根据你的实际使用场景调整事件类型,不用any更符合TS规范
interface DogsProps {
  onDogSelected: (e: React.ChangeEvent<HTMLSelectElement>) => void
  // 若有其他自定义props,可继续在该接口中添加
}
  1. 将声明的Props类型绑定到Dogs组件上:
    如果你用React.FC写法定义组件,将Props作为泛型传入即可:
const Dogs: React.FC<DogsProps> = (props) => {
  // 组件内部可以正常调用 props.onDogSelected
  // 示例:<select onChange={props.onDogSelected}>...</select>
}

如果不用React.FC写法,直接给参数加类型即可:

const Dogs = (props: DogsProps) => {
  // 组件内部逻辑同上
}

可选优化

你父组件中定义onDogSelected时的参数e可以替换为具体的事件类型,替代any获得更好的类型校验和提示:

// 若绑定在select下拉框则用该类型,其他元素替换为对应的元素类型即可
const onDogSelected = (e: React.ChangeEvent<HTMLSelectElement>) => {
  setDogSelected(e.target.value)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:06:04