【问题标题】:How to properly set the Gatsby.js homepage?如何正确设置 Gatsby.js 主页?
【发布时间】:2019-03-21 00:08:16
【问题描述】:

我正在使用 Gatsby 构建一个多页面网站(因此,多组件)。 在官方文档中,它说在 Layouts 文件夹中我应该有文件 index.js,它存储其他页面共有的组件(例如导航栏和页脚,就像一个反应路由器,这里命名为 MainNavBar 和 MainFooter)。 现在,index.js 文件也是主页和登录页面,当您到达 localhost:8000 位置时(上传后将是 www.mywebsite.com)。 问题是现在这个页面是空的,在网站中选择一个页面后,只呈现存储在 pages 文件夹中的 children()。但是,如果我在其中创建一个组件,例如主页(现在作为 home.js 存储在 pages 文件夹中),则其他页面将呈现在主页下方,并且主页本身将对所有其他页面,无法正确显示组件。 如何正确创建一个主页,该主页也是保持此配置的登录页面?

这是 index.js 组件

import Helmet from 'react-helmet'
import MainNavBar from '../components/navbar.js';
import Footer from '../components/footer';
import React, { Component } from 'react';
import logo from '../images/recsenz.png';
import tile1 from '../images/tile_imgs/prova(m).png';
import tile2 from '../images/tile_imgs/prova(d).png';
import tile3 from '../images/tile_imgs/prova(x).png';
import { Card, CardImg, CardText, CardBody,
   CardTitle, CardSubtitle, Button, Col, Row, Container } from 'reactstrap';
import PropTypes from 'prop-types';
import 'bootstrap/dist/css/bootstrap.min.css';


import './index.css'


const Layout = ({ children, data }) => (
  <div>
    <Helmet
      title={data.site.siteMetadata.title}
      meta={[
        { name: 'description', content: 'Sample' },
        { name: 'keywords', content: 'sample, something' },
      ]}
    />
    <MainNavBar />
      {children()}
    <Footer />      
  </div>
)

Layout.propTypes = {
  children: PropTypes.func,
}

export default Layout

export const query = graphql`
  query SiteTitleQuery {
    site {
      siteMetadata {
        title
      }
    }
  }
`

【问题讨论】:

  • 您是否有指向 Gatsby 文档的链接,该文档讨论“布局文件夹我应该有文件 index.js”。还提供链接代码或您的项目可能会有所帮助。如果您使用的是 Gatsby v2,那么您的组件文件夹中应该有一个 layout.js 文件。当您使用组件&lt;layout&gt; 包装任何“页面”时,该页面将继承“导航栏”或您希望始终显示的任何内容,而与路由无关。您页面文件夹中的Index.js 是根目录或主目录。

标签: javascript reactjs gatsby


【解决方案1】:

Gatsby (v2) 建议您设置工作目录的方法如下:

- src
 - components
  - layout.js
  - header.js
  - footer.js
 - pages
  - index.js
  - about.js

组件的命名完全取决于您。但是,在 pages 目录中,Gatsby 会根据其中的文件名自动创建页面。在上面的示例中,Gatsby 将使用index.js 创建您的主页,并使用about.js 创建一个“/about”页面。

建议您使用layout.js 组件来包装页眉和页脚等内容。这是一个例子:

layout.js

import React from "react"
import Header from "./header"
import Footer from "./footer"

export default ({ children }) => {
  return (
    <div id="main-content">
      <Header />
      {children}
      <Footer />
    </div>
  )
}

index.js

import React from "react"
import Layout from "../components/layout"

export default () => {
  return (
    <Layout>
      <h1>Welcome to my home page</h1>
    </Layout>
  )
}

关于.js

import React from "react"
import Layout from "../components/layout"

export default () => {
  return (
    <Layout>
      <h1>Welcome to my about page</h1>
    </Layout>
  )
}

【讨论】:

    猜你喜欢
    • 2014-08-10
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2020-05-31
    • 2011-03-13
    • 1970-01-01
    相关资源
    最近更新 更多