【问题标题】:Only change content using Gatsby Link仅使用 Gatsby Link 更改内容
【发布时间】:2020-04-16 17:12:41
【问题描述】:

我正在使用 GatsbyJS 构建一个站点,但期望路由器的行为会略有不同,因为它更像是 SPA 中的路由器,并且只会更改已更改的内容,而不是重新加载整个页面。

例如,如果我有:

<Link to="/next-page/">Go to Next Page</Link>

这会加载整个下一页并重新渲染所有内容。包括页眉、布局等。

我怎样才能让它只改变内容?

我注意到在 Gatsby 官方网站上就是这种行为,但实际上它似乎会加载并重新渲染整个下一页。您需要使用不同的组件吗?

例如,如果我有这三个文件:

layout.js

<div>
   <header>Header</header>
   <main>{children}</main>
</div>

index.js

<Layout>
  <Link to="/next-page/">Go to Next Page</Link>
</Layout>

下一页.js

<Layout>
  <Link to="/">Go to First Page</Link>
</Layout>

我希望在单击下一个链接时不应重新加载和呈现标题内容。因此,如果我通过 Web Inspector 更改标题的文本,我希望此文本不会更改,因为应该只更新网页的一部分。您可以在 Gatsby 网站上进行测试,方法是编辑标题 HTML 的任何部分,然后浏览并查看标题 HTML 永远不会重新呈现......但是如何?

【问题讨论】:

    标签: gatsby


    【解决方案1】:

    这成为 Gatsby v2 中的默认行为,但我发现同样的事情:希望全局布局保持不变是很常见的。您可以使用官方的gatsby-plugin-layout 插件重新添加该功能。

    运行以下命令:

    npm install --save gatsby-plugin-layout
    

    将插件添加到您的 gatsby-config.js 插件数组中:

    module.exports = {
      plugins: [
    
        // Etc…
    
        {
          resolve: `gatsby-plugin-layout`,
          options: {
            component: require.resolve(`./relative/path/to/layout/component`),
          },
        },
    
        // Etc…
    
      ],
    }
    

    ...带有布局组件的路径。

    更多背景:

    【讨论】:

      【解决方案2】:

      这些可以通过以下方式完成:

      const layout = (props) => {
          return (
            <Header />
            <Content
               {...props}
            />
            <Footer />
          )
      }
      

      Header.js

      const header = () => {
        return (
          <div>
           <p>some text</p>
          </div>
        )
      }
      

      Content.js

      const content = (props) => {
        return (
          <div>{ props.children } </div>
        )
      }
      

      Footer.js

      const footer = () => {
        return (
          <div>
           <p> some footer </p>
          </div>
        )
      }
      

      Header, Content, Footer 是独立的组件。

      您将使用整个页面的布局模板,并且您将在所有网站上使用相同的页眉和页脚。

      【讨论】:

      猜你喜欢
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      相关资源
      最近更新 更多