NextJS项目中MUI Link传入自定义组件触发Prop类型警告问题
解决MUI Link与Next.js Link结合时的Ref警告
我们的Next.js应用生产环境运行正常,本地渲染也无异常,但控制台会弹出一则不美观的警告,需要消除它。
警告信息
client.js:1 Warning: Failed prop type: Invalid prop `component` supplied to `ForwardRef(Link)`. Expected an element type that can hold a ref. Did you accidentally provide a plain function component instead? For more information see https://mui.com/r/caveat-with-refs-guide at Link (webpack-internal:///./node_modules/@mui/material/Link/Link.js:111:83) at Link (webpack-internal:///./src/components/Link.tsx:29:11) at span[...]
自定义Link.tsx代码
import { LinkProps, Link as MuiLink } from "@mui/material"; import NextLink, { LinkProps as NextLinkProps } from "next/link"; // Defining the CustomNextLink export type CustomNextLinkProps = Omit<NextLinkProps, "href"> & { _href: NextLinkProps["href"]; }; export const CustomNextLink = ({ _href, ...props }: CustomNextLinkProps) => { return <NextLink href={_href} {...props} />; }; // combine MUI LinkProps with NextLinkProps type CombinedLinkProps = LinkProps<typeof NextLink>; // we remove both href properties // and define a new href property using NextLinkProps export type MyLinkProps = Omit<CombinedLinkProps, "href"> & { href: NextLinkProps["href"]; }; export const Link = ({ href, ...props }: MyLinkProps) => { // use _href props of CustomNextLink to set the href return <MuiLink {...props} component={CustomNextLink} _href={href} />; };
解决方案
警告根源是MUI的Link组件要求传入的component必须支持ref传递,而当前的CustomNextLink是普通函数组件,默认无法接收ref。
只需两步修改:
- 用React的
forwardRef包裹CustomNextLink,让它能接收并传递ref给内部的NextLink:
import { forwardRef } from 'react'; export const CustomNextLink = forwardRef<HTMLAnchorElement, CustomNextLinkProps>( ({ _href, ...props }, ref) => { return <NextLink href={_href} {...props} ref={ref} />; } );
- 更新类型定义,让
CombinedLinkProps基于包裹后的CustomNextLink:
// 替换原CombinedLinkProps定义 type CombinedLinkProps = LinkProps<typeof CustomNextLink>;
修改完成后,MUI Link就能正确传递ref给CustomNextLink,控制台的警告会彻底消失。
内容的提问来源于stack exchange,提问作者Malcolm Crum
相关产品推荐
相关产品推荐

