NextJs 错误的解决方案是什么:“标题元素收到一个包含超过 1 个元素作为子元素的数组。”

Ble*_*obi 5 javascript reactjs next.js

创建一个组件来包装每个页面并希望接收每个页面的子级和标题会引发错误。“标题元素收到一个包含超过 1 个元素作为子元素的数组。”

import Head from "next/head";

interface IProps {
  children: JSX.Element;
  title?: string;
  restProps?: any;
}
export default function MetaDataContainer(props: IProps) {
  const {
    children,
    title = "Generated by create next app",
    ...restProps
  } = props;

  return (
    <>
      <Head>
        <title>CV-stack - {title}</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main className={styles.main}>{children}</main>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*emy 14

你需要提供一个像这样的对象

<title>{`CV-stack - ${title}`}</title>
Run Code Online (Sandbox Code Playgroud)

由于此评论中解释的原因(react dom字符串渲染)https://github.com/vercel/next.js/discussions/38256


Ble*_*obi 2

我在此链接上在线看到了解决方案。

下面是有效的示例代码:

import Head from "next/head";

interface IProps {
  children: JSX.Element;
  title?: string;
  restProps?: any;
}
export default function MetaDataContainer(props: IProps) {
  const {
    children,
    title = "Generated by create next app",
    ...restProps
  } = props;

  return (
    <>
      <Head>
        <title>{`CV-stack - ${title}`}</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main className={styles.main}>{children}</main>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

请注意,标题现在是带有 { CV-stack - ${title}} 的单个节点,而不是 CV 堆栈 - {title}