[英]Next.js default component value
I am trying to create a global variable that all components are rendered with by default and set that default value but I'm not sure how to do the 2nd part.我正在尝试创建一个全局变量,默认情况下所有组件都使用该变量进行渲染并设置该默认值,但我不确定如何执行第二部分。 Here's what I have so far in my
_app.tsx
:这是我到目前为止在
_app.tsx
中的内容:
import { AppProps } from "next/app";
import type { NextComponentType } from 'next'
import Blue from "../components/blue";
type CProps = AppProps & {
Component: NextComponentType & {model?: string }
};
const MyApp = ({
Component,
pageProps: { ...pageProps },
}: CProps) => {
return (
<>
{Component.model === 'blue' ? (
<Blue>
<Component {...pageProps} />
</Blue>
) : (
<Component {...pageProps} />
)}
</>
);
};
But this obviously doesn't give me a default value for model
.但这显然没有给我
model
的默认值。 It just creates that variable with null value for all the components.它只是为所有组件创建具有空值的变量。 How do I set the value?
如何设置值?
Side question: Is this better done using React Context?附带问题:使用 React Context 做得更好吗?
Edit 1: This is how the component sets the model value if it does not want to use the default value:编辑 1:如果组件不想使用默认值,这就是组件设置模型值的方式:
const ComponentFoo = () => {
return (
<>Test</>
);
};
ComponentFoo.model = 'red'
export default ComponentFoo;
This sounds like a good candidate for Next.js Layouts.这听起来像是 Next.js 布局的好候选。 You would have to compose a
Layout
component, similar to Blue
in your example, which accepts a color
prop and encapsulates the color rendering logic to the layout file.您必须编写一个
Layout
组件,类似于您的示例中的Blue
,它接受color
prop 并将颜色渲染逻辑封装到布局文件中。 You can implement a default render path if no color
prop is provided.如果没有提供
color
道具,您可以实现默认渲染路径。
Then you can use it like so:然后你可以像这样使用它:
// pages/whatever.tsx
import type { ReactElement } from 'react'
import Layout from '../components/layout'
export default function Page() {
return {
/** Your content */
}
}
Page.getLayout = function getLayout(page: ReactElement) {
return (
<Layout color="blue">
{page}
</Layout>
)
}
https://nextjs.org/docs/basic-features/layouts#with-typescript https://nextjs.org/docs/basic-features/layouts#with-typescript
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.