问题:
我有一个组件,应该重定向用户到一个新的页面点击。我想使用Next的<Link>组件来处理路由更改。
但是,我注意到,如果Link组件的任何子元素不是标准HTML元素(例如,<div>、<a>、.),则拒绝呈现。
在下面的示例中,我要呈现的组件是heroicons库中的一个图标。
MyPage.js
import Link from 'next/link'
import { ArrowSmRightIcon } from 'heroicons-react'
export default function MyPage() {
return(
<Link href='/targetPage'>
<ArrowSmRightIcon />
</Link>
)
}运行上述操作会出现以下错误:
错误:元素类型无效:预期为字符串(用于内置组件)或类/函数(用于组合组件),但未定义。
尝试解决办法:
我在网上找到了一些关于必须使用forwardRef创建自定义组件的建议。我已经将我的自定义组件实现为:
IconLink.js
import NextLink from 'next/link'
import { forwardRef } from "react";
import { ArrowSmRightIcon } from 'heroicons-react'
const IconLink = forwardRef(({ href, prefetch, replace, scroll, shallow, locale, ...props }, ref) => {
return(
<NextLink
href={href}
replace={replace}
scroll={scroll}
shallow={shallow}
locale={locale}
passHref
>
<ArrowSmRightIcon ref={ref} {...props} />
</NextLink>
)
})
export default IconLinkMyPage.js
从‘./ IconLink’导入IconLink;
export default function MyPage() {
return(
<IconLink
passHref
href='/targetPage'
/>
)
}然而,我仍然会遇到同样的错误。
我应该如何在Next的<Link>组件中呈现自定义子组件?
发布于 2022-10-06 09:07:49
问题不是来自下一个/链接,而是来自导入,此错误表示包中没有命名的导出"ArrowSmRightIcon“--我相信您正在寻找的是ArrowSmRight
import { ArrowSmRight } from 'heroicons-react'另外,如维护人员所述,不推荐该包:
这个包已经被废弃了
作者致辞:
官方Heroicons V1发布。请在未来的>项目中使用以下内容:https://www.npmjs.com/package/@heroicons/react
https://stackoverflow.com/questions/73970862
复制相似问题