【问题标题】:Can you use templates in Next.js?你可以在 Next.js 中使用模板吗?
【发布时间】:2021-04-21 20:24:52
【问题描述】:

我对 Web 开发相当陌生,目前有一个使用 Node.js、Express 和 Pug 的基本 Web 服务器,我希望将其转换为 Next.js。是否可以在 Next.js 中创建可重复使用的模板(类似于 Pug/Jade)?

【问题讨论】:

    标签: node.js express next.js


    【解决方案1】:

    这就是我的工作方式。有更好的方法,但这是我喜欢的方式。我来自快递车把,以前用过哈巴狗,所以我就是这样做的。

    在 pages/_app.js 文件中:

    import React from 'react'
    import Head from 'next/head'
    
    export default function MyApp({ Component, pageProps }) {
      const Layout = Component.Layout || LayoutEmpty // if page has no layout, it uses blank layout
      const PageTitle = Component.PageTitle // page title of the page
    
      return (
        <Layout>
          {PageTitle? (<Head><title>{PageTitle}</title></Head>) : '' }
          <Component {...pageProps} />
        </Layout>
      )
    }
    
    const LayoutEmpty = ({children}) => <>{children}</> // blank layout if doesnt detect any layout
    

    在您想要放置布局文件的组件文件夹中:例如 component/layout.js

    import Link from 'next/link';
    import {useRouter} from 'next/router'
    
    export function LayoutOne({children}) {
    try {
      return (<>
        <nav>
          <ul>
            <li><Link href="/"><a>Home</a></Link></li>
          </ul>
        </nav>
        <div>{children}</div>
      </>)
    } catch(e) {console.log(e)}
    }
    

    然后在您的页面中:例如 pages/about.js

    import React, { useState, useEffect } from 'react';
    import {LayoutOne} from '../component/layout' // location of your layout.js file
    
    Aboutpage.PageTitle = 'About | Website Tag Line' // set title of your page
    Aboutpage.Layout = LayoutOne // using LayoutOne. If you dont do this, its considered blank layout and you'll get no layout
    export default function Aboutpage() {
    try {
      return (
        <>
          <div>
            <h2>About</h2>
          </div>
        </>
      );
    } catch(e) {console.log(e)}
    }
    

    如果你想要更多的布局,在你的 layout.js 文件最后,只需更改导出函数的名称,例如:LayoutTwo

    export function LayoutTwo({children}) {
    try {
      return (<>
        <nav>
          <ul>
            <li><Link href="/dashboard"><a>Dashboard</a></Link></li>
          </ul>
        </nav>
        <div>{children}</div>
      </>)
    } catch(e) {console.log(e)}
    }
    

    一页,您将布局更改为两个

    import {LayoutTwo} from '../component/layout'
    Aboutpage.Layout = LayoutTwo
    

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 2013-09-23
      • 2013-07-13
      • 1970-01-01
      相关资源
      最近更新 更多