完善文章頁面
為文章頁面添加 title
在 pages/posts/[id].js
中,我們將使用文章數據來添加 title
標籤。你需要在文件頂部添加 next/head
的導入,並通過更新 Post
組件來添加 title
標籤:
// 添加此導入
import Head from 'next/head';
export default function Post({ postData }) {
return (
<Layout>
{/* 添加此 <Head> 標籤 */}
<Head>
<title>{postData.title}</title>
</Head>
{/* 保留此處的現有代碼 */}
</Layout>
);
}
格式化日期
為了格式化日期,我們將使用 date-fns
庫。首先,安裝它:
npm install date-fns
接下來,創建一個名為 components/date.js
的文件,並添加以下 Date
組件:
import { parseISO, format } from 'date-fns';
export default function Date({ dateString }) {
const date = parseISO(dateString);
return <time dateTime={dateString}>{format(date, 'LLLL d, yyyy')}</time>;
}
注意:你可以在 date-fns 網站上查看不同的
format()
字符串選項。
現在,打開 pages/posts/[id].js
,在文件頂部添加 Date
組件的導入,並用它替換 {postData.date}
:
// 添加此導入
import Date from '../../components/date';
export default function Post({ postData }) {
return (
<Layout>
{/* 保留此處的現有代碼 */}
{/* 用以下代碼替換 {postData.date} */}
<Date dateString={postData.date} />
{/* 保留此處的現有代碼 */}
</Layout>
);
}
如果你訪問 http://localhost:3000/posts/pre-rendering,現在應該會看到日期顯示為 "January 1, 2020"。
添加 CSS
最後,讓我們使用之前添加的 styles/utils.module.css
文件來添加一些 CSS。打開 pages/posts/[id].js
,然後在文件頂部添加 CSS 文件的導入,並將 Post
組件替換為以下代碼:
// 在文件頂部添加此導入
import utilStyles from '../../styles/utils.module.css';
export default function Post({ postData }) {
return (
<Layout>
<Head>
<title>{postData.title}</title>
</Head>
<article>
<h1 className={utilStyles.headingXl}>{postData.title}</h1>
<div className={utilStyles.lightText}>
<Date dateString={postData.date} />
</div>
<div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />
</article>
</Layout>
);
}
如果你訪問 http://localhost:3000/posts/pre-rendering,現在頁面應該看起來更美觀了:
做得很好!接下來我們將完善首頁,然後就大功告成了!