【发布时间】:2021-10-05 07:20:25
【问题描述】:
我是打字稿的新手,在将函数“toggle”作为道具传递给样式化组件“MobileIcon”时遇到打字稿错误。 我已经在接口 IProps 中设置了“toggle”的函数类型并将其添加到 styled-component 中。
Layout.tsx:
import { FunctionComponent as FC, ReactNode, useState } from "react";
import Toolbar from "src/components/Toolbar";
interface IProps {
main: ReactNode;
}
const Layout: FC<IProps> = ({ main }) => {
const [isOpen, setIsOpen] = useState<boolean>(false);
const toggle = () => {
setIsOpen(!isOpen);
console.log("toggle ok");
};
return (
<div>
<nav>
<Toolbar isOpen={isOpen} toggle={toggle} />
</nav>
<main>{main}</main>
</div>
);
};
export default Layout;
Toolbar.tsx:
import { FunctionComponent as FC } from "react";
import styled from "styled-components";
import Link from "next/link";
// Components
import Brand from "./Brand";
interface IProps {
isOpen: boolean;
toggle: () => void;
}
const Toolbar: FC<IProps> = ({ isOpen, toggle }) => {
return (
<Container>
<Link href="/">
<a>
<Brand />
</a>
</Link>
<MobileIcon isOpen={isOpen} onClick={toggle}>...</MobileIcon>
</Container>
);
};
export default Toolbar;
样式化组件:
const MobileIcon = styled.div<IProps>`
...
`
错误:
No overload matches this call.
Overload 1 of 2, '(props: Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "key" | keyof HTMLAttributes<...>> & { ...; } & IProps, never> & Partial<...>, "theme"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.
Property 'toggle' is missing in type '{ children: Element[]; isOpen: boolean; onClick: () => void; }' but required in type 'Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "key" | keyof HTMLAttributes<HTMLDivElement>> & { ...; } & IProps, never> & Partial<...>, "theme">'.
Overload 2 of 2, '(props: StyledComponentPropsWithAs<"div", any, IProps, never, "div", "div">): ReactElement<StyledComponentPropsWithAs<"div", any, IProps, never, "div", "div">, string | JSXElementConstructor<...>>', gave the following error.
Property 'toggle' is missing in type '{ children: Element[]; isOpen: boolean; onClick: () => void; }' but required in type 'Omit<Omit<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "key" | keyof HTMLAttributes<HTMLDivElement>> & { ...; } & IProps, never> & Partial<...>, "theme">'.
任何帮助都会很棒。
【问题讨论】:
-
贴出MobileIcon范围内的IProps接口,感觉你叫onClick
标签: reactjs typescript next.js styled-components