所以下面的代码有效:
const HomePage: NextPage = () => (
<div>
<div>HomePage</div>
</div>
);
但是我想遵守 Airbnb 的风格指南,在这种情况下,它要求您使用命名函数,得到以下代码:
function HomePage(): NextPage {
return (
<div>
<div>HomePage</div>
</div>
)
}
但是编译器对上面的代码给出了以下错误:
Type 'Element' is not assignable to type 'NextPage<{}, {}>'.
Type 'ReactElement<any, any>' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
Type 'ReactElement<any, any>' is not assignable to type 'FunctionComponent<{}>'.
Type 'ReactElement<any, any>' provides no match for the signature '(props: { children?: ReactNode; }, context?: any): ReactElement<any, any> | null'.ts(2322)
我可以通过不指定类型或将返回强制转换为 as unknown as NextPage
来绕过错误,这两种方法看起来都像是变通方法而不是正确的解决方案。
在这种情况下使用命名函数的正确方法是什么?
最佳答案
这两个代码块并不完全相同。
在第一个中,您正确地使用 NextPage
来键入函数变量 HomePage
。
在第二个中,您错误地使用了 NextPage
来键入 HomePage
的返回值(这与功能本身)。
您可以使用JSX.Element
、React.ReactElement
或React 等多种方式键入
.HomePage
的返回值。 ReactNode
function HomePage(): JSX.Element {
return (
<div>
<div>HomePage</div>
</div>
)
}
请注意,在第一个代码块中键入函数并没有错,这实际上是 Next.js 中推荐的方式。它为组件的属性和返回值提供类型。
关于reactjs - 使用返回类型为 NextPage 的函数时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71144514/