Dav*_*uri 2 javascript typescript reactjs tsx next.js
在使用 Next.js 开发我的个人作品集时,我遇到了一个错误,即“children”道具不起作用。我正在使用 tsx.
布局.tsx
import styles from "./layout.module.css";
export default function Layout({ children, ...props }) {
return (
<>
<main className={styles.main} {...props}>{children}</main>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用其他道具,定义道具,就像我在网上教程中所做的那样,但它们都不起作用。;(
您的文件类型是 .tsx,它是 TypeScript 文件类型。您必须定义 props 的类型,或者将文件名更改为 Layout.js 以将其转换为普通 JavaScript。
如果你想使用 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>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
问题是,当 TypeScript 不知道type某些东西的类型时,它会假设该类型是any并且抱怨。您也可以显式设置类型来any解决此问题,但这被认为是不好的做法:
export default function Layout({ children, ...props }: any) {
return (
<>
<main className={styles.main} {...props}>{children}</main>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3745 次 |
| 最近记录: |