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

React组件onClick类型定义报错:如何正确扩展或覆盖类型?

Hey there, let's fix that TypeScript error in your React component. The problem here is that using Function for your onClick prop is too vague—React expects a specific type for event handlers that matches what native elements like <button> use.

First, let's update your interface to use React's built-in event handler type instead of Function. Here's how:

import React from 'react';
// Assuming SpaceProps is imported from your source

export interface IClearButton extends SpaceProps {
  onClick: React.MouseEventHandler<HTMLButtonElement>;
}

export const ClearButton: React.FC<IClearButton> = ({ onClick }) => {
  return (
    <button onClick={onClick}>
      <SomeComponent />
    </button>
  );
};

This works because React.MouseEventHandler<HTMLButtonElement> is exactly the type that the native button's onClick prop expects—it's a function that receives a mouse event object and returns void. This keeps your code type-safe and eliminates the error.

If you prefer to write the function type explicitly instead of using the shorthand, you can do this too:

export interface IClearButton extends SpaceProps {
  onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
}

Both approaches are equivalent and will resolve the issue. The key is to match the type that React uses for button click handlers, rather than using the generic Function type which doesn't carry any information about the arguments or return value.

That strange error about onClick not existing on the combined type was likely a side effect of using the incorrect Function type—once you switch to the proper React event handler type, that should disappear as well.

Avoiding any is the right call here, since it removes all type safety. Using the built-in React types ensures that your component's onClick prop behaves exactly like a native button's, which is intuitive for anyone using your component.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:56:27