React/Next.js传递props.children与组件作为props时报错求助
解决思路
核心问题原因
React 规定组件标签必须以大写字母开头,直接使用props.component这种小写开头的变量作为组件标签,会被识别为普通HTML元素而非React组件,从而抛出构造/调用签名错误。
具体修复步骤
1. 修正组件变量命名(关键)
在UserShell组件内部,先将props.component赋值给一个大写开头的变量,再使用这个变量作为组件标签,同时增加判空逻辑避免空组件报错:
type ShellProps = { children: React.ReactNode | React.ReactNode[]; component?: React.ComponentType; }; export default function UserShell(props: ShellProps) { // 将props.component赋值给大写开头的变量 const Component = props.component; return ( <> {Component && <Component />} <div>{props.children}</div> </> ); }
2. 修正Layout.tsx中的组件调用笔误
你在Layout.tsx里写的<User />应为<UserShell />(因为导入的组件是UserShell),修正后代码:
import UserShell from "./account/User"; import Breadcrumb from "./navigation/Breadcrumb"; <UserShell component={Breadcrumb}>{props.children}</UserShell>;
可选优化:支持传递组件props
如果需要给传入的component传递自定义props,可以完善类型定义:
type ShellProps<T = {}> = { children: React.ReactNode | React.ReactNode[]; component?: React.ComponentType<T>; componentProps?: T; }; export default function UserShell<T = {}>(props: ShellProps<T>) { const Component = props.component; return ( <> {Component && <Component {...props.componentProps} />} <div>{props.children}</div> </> ); }
这样后续给Breadcrumb传props时能获得完整的TypeScript类型提示。
内容的提问来源于stack exchange,提问作者tdev
相关产品推荐
相关产品推荐

