在React/Nextjs中传递prop.children和组件作为prop

tsm1rwdh  于 2022-12-23  发布在  React
关注(0)|答案(2)|浏览(232)

User.tsx是一种导航栏,它通过{props.children}传递所有子组件。我还想向它传递一个breadcrumb组件,但我收到一个错误消息:
JSX元素类型“prop.component”没有任何构造或调用签名
Layout.tsx:

import UserShell from "./account/User
 import Breadcrumb from "./navigation/Breadcrumb";
 <User component={Breadcrumb}>{props.children}</User>;

User.tsx:

type ShellProps = {
  children: React.ReactNode | React.ReactNode[];
  component?: React.ComponentType;

export default function UserShell(props: ShellProps) {
 return (
    <>
      <props.component />
      ^^^^^^^^^^^^^^^^^^//error is here

      <div>{props.children}</div>
    </>
}

有什么解决办法吗?

xytpbqjk

xytpbqjk1#

import React from 'react'

type ShellProps = {
    children: React.ReactNode | React.ReactNode[];
    component?: React.ComponentType;
}

function UserShell(props: ShellProps) {
    return (
        <>
            {props.component ? <props.component /> : null}
            <div>{props.children}</div>
        </>
}

运动场
您可能需要大写组件(Component)

sbtkgmzw

sbtkgmzw2#

尝试更新到此
Layout.tsx:

import UserShell from "./account/User
 import Breadcrumb from "./navigation/Breadcrumb";
 <User Breadcrumb={Breadcrumb}>{props.children}</User>; //use Breadcrumb or Component (capital C)

User.tsx

type ShellProps = {
  children: React.ReactNode | React.ReactNode[];
  Breadcrumb?: React.ElementType; //covers all elements

export default function UserShell({Breadcrumb, children}) {
 return (
    <>
      <Breadcrumb/>
      <div>{children}</div>
    </>
}

相关问题