使用next-intl的useTranslations时触发ForwardRef(Box)的ReactNode警告
解决next-intl useTranslations()触发的MUI Box children警告问题
问题原因
你看到的Invalid prop 'children' supplied to 'ForwardRef(Box)'警告,根源在于**FeaturedListings组件被标记为服务器组件("use server"),但你在里面使用了客户端钩子useTranslations()**。
Next.js中,服务器组件不能调用客户端钩子,这种混用会导致组件渲染出非预期结果,最终触发MUI组件的children类型校验失败。
解决方案
有两种方式可以解决这个问题,根据你的组件需求选择:
方式一:转为客户端组件(最直接)
移除"use server"指令,同时显式添加'use client'声明组件为客户端组件,这样就能正常使用useTranslations()钩子:
// FeaturedListings.tsx 'use client'; import { FC } from "react"; import { useTranslations } from "next-intl"; import { Grid, Typography, Box, Container } from "@mui/material"; import { FeaturedListingsProps } from "./Types"; const FeaturedListings: FC<FeaturedListingsProps> = () => { const t = useTranslations(); return ( <Grid container spacing={4}> <Grid item xs={12}> <Typography variant="h3">{t("Metatags.Landing.title")}</Typography> </Grid> </Grid> ); }; export default FeaturedListings;
方式二:保留服务器组件,使用服务器端翻译
如果这个组件需要保持服务器组件的特性,改用next-intl提供的服务器端翻译方法getTranslations(),注意组件要定义为异步函数:
// FeaturedListings.tsx import { FC } from "react"; import { getTranslations } from "next-intl/server"; import { Grid, Typography, Box, Container } from "@mui/material"; import { FeaturedListingsProps } from "./Types"; const FeaturedListings: FC<FeaturedListingsProps> = async () => { const t = await getTranslations(); return ( <Grid container spacing={4}> <Grid item xs={12}> <Typography variant="h3">{t("Metatags.Landing.title")}</Typography> </Grid> </Grid> ); }; export default FeaturedListings;
关键说明
- 客户端钩子(如
useTranslations())只能在标记了'use client'的组件中使用,服务器组件(包括带"use server"的组件)不支持调用客户端钩子。 - 服务器组件中使用异步翻译方法时,组件必须是async函数,父组件如果是服务器组件可以直接渲染该异步组件。
内容的提问来源于stack exchange,提问作者Ariful
相关产品推荐
相关产品推荐

