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

React函数组件Props中注入的add函数应定义何种TypeScript类型?

解决React组件中自定义回调的TypeScript类型问题

嘿,作为React+TypeScript新手,你遇到的这个问题其实很常见——因为你这里的onClick根本不是原生的鼠标点击事件回调,而是一个自定义的业务逻辑回调,所以React提供的鼠标事件类型当然不适用啦!我来帮你一步步修正类型定义:

问题核心

你的Description2组件里的onClick属性,是用来把组件内部的count和incrementBy传递给父组件的add函数,它的参数是两个数字,而不是鼠标事件对象。所以我们需要给它定义匹配函数签名的明确类型,而不是用any。

修正步骤

  1. 修正Props接口的类型定义
    首先把IProps里的onClick: any替换成和add函数完全匹配的类型,同时如果父组件一定会传递count和incrementBy,建议去掉可选标记?,避免后续出现undefined的类型错误:

    interface IProps {
      count: number;
      incrementBy: number;
      onClick: (currentCount: number, bump: number) => void;
    }
    
  2. 确保组件调用回调时参数类型正确
    现在props.count和props.incrementBy都是明确的number类型,所以按钮的点击回调里直接传递这两个值就完全符合类型要求了,不需要额外处理。

完整修正后的代码

import React, { useState } from 'react';

interface IProps {
  count: number;
  incrementBy: number;
  onClick: (currentCount: number, bump: number) => void;
}

const Description2: React.FC<IProps> = (props) => (
  <div>
    <p>My favorite number is {props.count}, incrementing by {props.incrementBy}</p>
    <button onClick={() => props.onClick(props.count, props.incrementBy)}>
      Increase
    </button>
  </div>
);

const App: React.FC = () => {
  const increase = 4;
  const [count, setCount] = useState(increase);
  const [user, setUser] = useState("world");

  const add = (currentCount: number, bump: number) => {
    setCount(currentCount + bump);
  };

  return (
    <div>
      <Description2 count={count} incrementBy={increase} onClick={add} />
    </div>
  );
}

export default App;

额外说明

如果之后你的count或incrementBy可能变成可选属性(比如父组件不一定传递),那需要在类型里保留?,同时在调用回调时处理undefined的情况,比如:

interface IProps {
  count?: number;
  incrementBy?: number;
  onClick: (currentCount: number, bump: number) => void;
}

// 在组件里调用时加默认值
<button onClick={() => props.onClick(props.count ?? 0, props.incrementBy ?? 1)}>
  Increase
</button>

这样就能彻底告别any类型,让你的代码类型安全啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:35:01