Reactjs Typescript,已设置样式的组件错误:TS2769:没有与此调用匹配的重载。过载1/2
这是我的styledComponent:Reactjs Typescript,已设置样式的组件错误:TS2769:没有与此调用匹配的重载。过载1/2,reactjs,typescript,styled-components,Reactjs,Typescript,Styled Components,这是我的styledComponent: const stopPropagation = (event: Event): void => { event.stopPropagation(); }; <StyledComp onClick={stopPropagation}> //error occurs here hi StyledComp </StyledComp> 错误消息的重要部分是 类型“(事件:事件)=>void”不可分配给类型“(事件:M
const stopPropagation = (event: Event): void => {
event.stopPropagation();
};
<StyledComp onClick={stopPropagation}> //error occurs here
hi StyledComp
</StyledComp>
错误消息的重要部分是 类型“(事件:事件)=>void”不可分配给类型“(事件:MouseEvent)=>void” 因此,样式化div的
onClick
属性的类型为(event:MouseEvent)=>void
,您希望为其分配(event:event)=>void
类型的函数,但这不起作用,因为这些类型不兼容
你应该写:
const stopPropagation = (event: MouseEvent<HTMLDivElement, MouseEvent>): void => {
event.stopPropagation();
};
const stopPropagation=(事件:MouseEvent):void=>{
event.stopPropagation();
};
我不确定什么是事件
,但恐怕没有这样的内置静态类型。因此,如果您没有手动定义它,您必须使用React.MouseEvent
来代替。我手动定义了它,它与React.MouseEvent.Oh相同,可能我对事件类型的看法是错误的。让我来调查一下,也许是问题。谢谢,我添加了这个类型:React.MouseEvent,它成功了。我只是想给这个正确答案添加一点注释。只要像这样从react导入MouseEvent,这个答案就是正确的:import{MouseEvent}from'react'
。用于限制性事件处理的MouseEvent是不必要的,也没有意义,因此,如果您想使用限制性方法,您可以像这样做:MouseEvent
,或者对于一般用法,您只需单独使用MouseEvent
。
export type Event = {
target: {
value: string;
};
stopPropagation: () => void;
preventDefault: () => void;
};
const stopPropagation = (event: MouseEvent<HTMLDivElement, MouseEvent>): void => {
event.stopPropagation();
};