next.js - 如何从 _app.js 中排除默认组件,使其无法在 slug 中呈现
问题描述
我已经阅读了 Next.Js 的文档,我了解到通过创建一个 _app.js 文件,它将覆盖默认的 App.js 文件,因此 _app.js 文件中的那些组件将显示在每个页面上,这就是我需要的, 但我还需要排除其中一些组件在 slug 中呈现,例如页眉或页脚,我想在除 slug 之外的所有页面上显示它们,我该怎么做?
这是我的 _app.js 代码
import React from 'react'
import Head from 'next/head';
import { ThemeProvider } from '@material-ui/core/styles';
import Header from '@/components/Header/Header'
import theme from '@/theme/theme';
function MyApp({ Component, pageProps }) {
return (
<Head>
<title>My App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<ThemeProvider theme={theme}>
<Header />
<main>
<Component {...pageProps} />
</main>
</ThemeProvider>
)
}
这是我的蛞蝓
import React from 'react'
const MyAccounts = ({ data }) => {
const post = data && data.posts[0]
return (
<>
<div>
<article>
{post.feature_image ?
<figure >
<img src={post.feature_image} alt={post.title} />
</figure> : null}
<section >
<h1>{post.title}</h1>
</section>
</article>
</div>
</>
)
}
export default MyAccounts
因此,在此代码中,我不希望组件 Head 显示在我的 slug 中,我该如何排除它?
解决方案
在_app.js
您拥有 的情况下pageProps
,您可以利用它。在其中设置一些属性并基于它进行渲染。
就像是:
function MyApp({ Component, pageProps }) {
return (
<Head>
<title>My App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<ThemeProvider theme={theme}>
{pageProps.noLayout ? <></> : <Header />}
<main>
<Component {...pageProps} />
</main>
</ThemeProvider>
)
}
然后在页面上添加例如:
export async function getStaticProps(context) {
return {
props: { noLayout: true },
}
}
推荐阅读
- java - 如果条件不满足,如何跳过映射元素
- c++ - ESP32 和 PCF8574 编码器双脉冲
- c - 'pthread_create' 在我的 UBUNTU 20.04 中无法识别
- r - 如何在 GitLab 的分支中使用函数
- reactjs - 如何在material-ui makestyles上应用打字稿自动完成类型
- java - 与休眠 5.4 兼容的弹簧芯
- php-7.4 - Illuminate\Contracts\Container\BindingResolutionException 目标类 [FeaturesController] 不存在。在 Laravel 42.8 和 php 7.4
- python - Python,强制像素值在 [0,1] 范围内
- php - WordPress 自定义用户角色的问题 - 没有权限
- django - 根据另一个字段中的选择动态填充一个 Django 表单字段