Afs*_*fda 5 typescript reactjs styled-components
这是我的 styledComponent:
\nconst stopPropagation = (event: Event): void => {\n event.stopPropagation();\n};\n\n<StyledComp onClick={stopPropagation}> //error occurs here\n hi StyledComp\n</StyledComp>\nRun Code Online (Sandbox Code Playgroud)\n这就是我的定义:
\nexport type Prop = {\n onClick: (event: Event) => void;\n};\n\nexport const StyledComp = styled.div<Prop>`\n display: flex;\n`;\nRun Code Online (Sandbox Code Playgroud)\n但它返回一个错误,例如:
\n\n\nTS2769:没有与此调用匹配的重载。\xc2\xa0\xc2\xa0Overload 1 of 2, \'(props: Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes, HTMLDivElement>, "title" | "slot" | ... 252 更多 ... | "is" > & { ...; } & StyledComp, "标题" | ... 254 个以上 ... | "is"> & Partial<...>, "标题" | ... 254 个以上 ... | " is"> & { ...; } & { ...; }): ReactElement<...>\',给出以下错误。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type \'(event: Event) => void\' 不可分配给类型 \'((event: MouseEvent<HTMLDivElement, MouseEvent>) => void) & ((事件: 事件) => void)\'. \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type \'(event: Event) => void\' 不可分配给类型 \'(event: MouseEvent<HTMLDivElement,鼠标事件>) => void\'。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0参数\'event\'和\'event\'的类型不兼容。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type \'MouseEvent<HTMLDivElement, MouseEvent>\'不可分配给类型“Event”。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0属性类型“目标”不兼容。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2 \xa0\xc2\xa0Property \'value\' 在类型 \'EventTarget\' 中缺失,但在类型 \'{ value: string; 中需要 }\'。\xc2\xa0\xc2\xa0Overload 2 of 2, \'(props: StyledComponentPropsWithAs<"div", any, StyledComp, never>): ReactElement<StyledComponentPropsWithAs<"div", any, StyledComp, never>, string | ... 1 更多... | (new (props: any) => Component<...>)>\',给出了以下错误。\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type \'(event: Event) => void\' 不可分配给类型 \'((event: MouseEvent<HTMLDivElement, MouseEvent>) => void) & ((事件: 事件) => void)\'. \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0Type \'(event: Event) => void\' 不可分配给类型 \'(event: MouseEvent<HTMLDivElement,鼠标事件>) => void\'。
\n
注意:您可以在这里找到 styled-component&Typescript 文档!
\n编辑:
\n这是事件类型:
\nexport type Event = {\n target: {\n value: string;\n };\n stopPropagation: () => void;\n preventDefault: () => void;\n};\nRun Code Online (Sandbox Code Playgroud)\n
错误消息的重要部分是
类型“(event: Event) => void”不可分配给类型“(event: MouseEvent<HTMLDivElement, MouseEvent>) => void”
因此,onClick样式化 div 的属性具有类型(event: MouseEvent<HTMLDivElement, MouseEvent>) => void,并且您想为其分配类型的函数(event: Event) => void,但这不起作用,因为类型不兼容。
你应该这样写:
const stopPropagation = (event: MouseEvent<HTMLDivElement, MouseEvent>): void => {
event.stopPropagation();
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6964 次 |
| 最近记录: |