我最近更新了Gatsby从V3到V4(最新的),并更新了下面的插件。
"@mdx-js/mdx": "^2.1.3",
"@mdx-js/react": "^2.1.3",
"gatsby-plugin-mdx": "^4.1.0",
"gatsby": "^4.21.1",node-config.js中的代码-
{
resolve: `gatsby-plugin-mdx`,
options: {
defaultLayouts: { default: require.resolve(`./src/components/layout`), },
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages/`,
},
},在/src/pages/index.mdx中
---
title: Title
description: Description
class: home
imageTwitter: /twitter-home.jpg
imageOg: "/og-home.jpg"
imageAlt: Image for the Title.
---
import { StaticImage } from "gatsby-plugin-image"
import { Container, Row, Col, Card } from "react-bootstrap"
import { Link } from "gatsby"
import { navigate } from "gatsby"
<div class="w-60 text-center home-intro">
content
</div>最新版本的gatsby没有defaultLayout,所以当我点击http://localhost:8000/时,页面加载时没有页眉和页脚,因为布局不工作。
在/src/components/layout.js中
import React from "react"
import PropTypes from "prop-types"
import { StaticQuery, graphql } from "gatsby"
import { Container, Row, Col } from "react-bootstrap"
import "../styles.scss"
import Footer from "./footer"
import Menu from "./menu"
import Helmet from "react-helmet"
const Layout = ({ location, children, pageContext, ...props }) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
siteUrl
}
}
allMdx {
edges {
node {
frontmatter {
title
description
class
imageOg
imageTwitter
}
}
}
}
}
`}
render={data => (
<>
<Helmet>
<body className={pageContext.frontmatter.class} />
</Helmet>
<Container>
<Row>
<Col>
<Menu />
</Col>
</Row>
</Container>
<Container className="full-width">
<Row className="mx-0">
<Col>
<main>
<article id="content">
{children}
</article>
</main>
</Col>
</Row>
</Container>
<Footer />
</>
)}
/>
)
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout是否可以在页面目录中创建默认模板,然后将每个MDX文件作为子文件引用?例如,如果它的索引页,那么它将选择home.mdx
任何帮助都是非常感谢的。
发布于 2022-09-02 14:32:16
根据迁移指南,您有几个选项可以在动态页面创建中使用公共布局:
wrapPageElement API,包括它的SSR。export default Layout语句添加到MDX文件中,请参见关于布局的MDX文档。your-layout-component.js?__contentFilePath=absolute-path-to-your-mdx-file.mdx。要了解这方面的更多信息,请访问以编程方式创建页面指南。考虑到您的场景,我认为选项2和3更适合,因为它们很容易实现,而且与您已经拥有的任何东西相比,冲突的更改更少。明智地选择,任何适合您的规范(如果您正在或不使用gatsby-node.js,使用全局包装作为Redux,等等)。
选项2
如果您定义了一个Layout,它将用于包装所有内容。可以使用默认导出从MDX内部定义布局:
export default function Layout({children}) {
return <main>{children}</main>;
}
All the things.或者:
export {Layout as default} from './components.js'布局也可以作为components.wrapper传递(但本地布局优先)。
选项3
在gatsby-node.js中,在生成页面时,需要指向布局如下:
createPage({
path: `/some-slug/`,
component: `layout-component.js?__contentFilePath=${absolute-path-to-your-mdx-file.mdx}`,
context: {
id: `123456`,
},
})注意:这种方法可能会迫使您稍微调整一下GraphQL查询,以添加所需的数据以正确构建__contentFilePath。
https://stackoverflow.com/questions/73583766
复制相似问题