[英]TypeScript in React: 'No Overload Matches this Call' when using optional function parameters in interface
我正在尝试创建 2 种类型的开关,其中一种需要访问 click 事件。 我已经将我的道具接口如下:
interface SectionProps {
title: string;
options: {
flavorText: string;
toggle: (e?: React.MouseEvent<HTMLDivElement>) => void;
checked: boolean;
};
inputStyle: SelectionsType;
/**an array of desired tile displays if using tile inputs */
tileLabels?: string[];
}
我正在传递 onChange(对于复选框输入)或 onClick(对于我的 tile 输入,它们是 div)的切换函数,如下所示:
{inputStyle === 'checkbox' && (
<Switch
type="checkbox"
onChange={options.toggle}
checked={options.checked}
></Switch>
)}
{inputStyle === 'tiles' && (
<TileSwitch
isActive={options.checked}
onClick={e => options.toggle(e)}
>
{tileLabels?.map((tile, i) => (
<TileName key={i}>{tile}</TileName>
))}
</TileSwitch>
)}
我只需要为 tile 输入传递事件,所以我用e?
接口中的参数。 但是,我在<Switch>
的onChange
道具上遇到错误,说No overload matches this call.
有Type '(e?: MouseEvent<HTMLDivElement, MouseEvent> | undefined) => void' is not assignable to type '(event: ChangeEvent<HTMLInputElement>) => void'
错误,最终说Type '(e?: MouseEvent<HTMLDivElement, MouseEvent> | undefined) => void' is not assignable to type '(event: ChangeEvent<HTMLInputElement>) => void'
我不确定为什么 onChange 期望在它是可选的时接收事件参数。 有没有更好的方法来选择性地通过接口传递函数参数?
定义toggle: (e?: React.MouseEvent<HTMLDivElement>) => void;
说可以用 0 或 1 个参数调用toggle
。 如果使用一个参数调用它,则该参数必须是React.MouseEvent<HTMLDivElement>
类型。
Switch
的onChange
属性会以一个参数调用,即 switch 的 change 事件。 当您像这样将函数传递给onChange
: <Switch onChange={options.toggle} />
,您是在告诉Switch
调用options.toggle
及其更改事件。
因此,您会收到您发布的错误,因为Switch
组件正在使用ChangeEvent<HTMLInputElement>
类型的事件调用options.toggle
,这不是options.toggle
可接受的参数,它只能接受React.MouseEvent<HTMLDivElement>
类型的事件React.MouseEvent<HTMLDivElement>
。
为了不带参数调用回调,你想写这个: <Switch onChange={() => options.toggle()} />
。 这会忽略事件参数并阻止它被传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.