admin管理员组

文章数量:1356764

While developing my personal portfolio using Next.js, I ran into an error where the prop "children" was not working. I am using tsx.

Layout.tsx

import styles from "./layout.module.css";

export default function Layout({ children, ...props }) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

I tried using other props, defining the props, like I was from tutorials online, but none of them worked. ;(

While developing my personal portfolio using Next.js, I ran into an error where the prop "children" was not working. I am using tsx.

Layout.tsx

import styles from "./layout.module.css";

export default function Layout({ children, ...props }) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

I tried using other props, defining the props, like I was from tutorials online, but none of them worked. ;(

Share Improve this question asked Dec 3, 2022 at 19:56 David GuriDavid Guri 1631 silver badge10 bronze badges 1
  • Those fragments (<>) are not necessary. You can learn more here: reactjs/docs/fragments.html – ddblair Commented Dec 3, 2022 at 20:10
Add a ment  | 

2 Answers 2

Reset to default 8

Your filetype is .tsx, which is a TypeScript filetype. You have to either define the types of the props, or change the file's name to Layout.js to convert it to vanilla JavaScript.

If you want to use TypeScript:

import { ReactNode } from "react";
import styles from "./layout.module.css";

const type LayoutProps = {
  children: ReactNode;
  // Your other props here.
}

export default function Layout({ children, ...props }: LayoutProps) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

The issue is that when TypeScript doesn't know the type of something, it will assume the type is any and plain. You could explicitly set the type as any to solve this problem, as well, but this is considered bad practice:

export default function Layout({ children, ...props }: any) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

One way to define a layout.tsx file in typescript with Next.js 14+ we can import the LayoutProps:

import { LayoutProps } from "@/.next/types/app/page";
import styles from "./layout.module.css";

export default function Layout({ children, ...props }: LayoutProps) {
    return (
    <>
        <main className={styles.main} {...props}>{children}</main>
    </>

); }

本文标签: javascriptBinding element 39children39 implicitly has an 39any39 typets(7031) in NextjsStack Overflow