node.js - 你可以在 Next.js 中使用模板吗?
问题描述
我对 Web 开发相当陌生,目前有一个使用 Node.js、Express 和 Pug 的基本 Web 服务器,我希望将其转换为 Next.js。是否可以在 Next.js 中创建可重复使用的模板(类似于 Pug/Jade)?
解决方案
这就是我的做法。有更好的方法,但这是我喜欢的方式。我来自快速车把,以前用过哈巴狗,所以我就是这样做的。
在 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
推荐阅读
- python - 从 CSV 文件中的数据字符串中提取信息
- javascript - 如何在 nodejs 和 mongodb 中制作搜索 api
- javascript - In Vue.js, how can I get an event to fire in a select when the displayed element is chosen?
- reactjs - 如何修复状态变量内容不显示
- java - Kotlin:如何将带有 HTML 数字的字符串转换为不带 HTML 数字的字符串
- wordpress - 我正在尝试在 busiprof 主题中编辑 index-slider.php 文件,但它不会改变任何东西
- java - GWT.create(MyClass.class) 给出 MyClass 必须是类的错误
- javascript - 历史 API 的状态不会保留在已部署的应用程序中
- android - Android recyclerview 未在第一次尝试时设置项目
- javascript - Angular中语句的含义