34
章节34
美化文章页面
为文章页面添加 title
在 pages/posts/[id].js 中,让我们使用文章数据添加 title 标签。你需要在文件顶部添加 next/head 的导入,并通过更新 Post 组件来添加 title 标签
// Add this import
import Head from 'next/head';
export default function Post({ postData }) {
return (
<Layout>
{/* Add this <Head> tag */}
<Head>
<title>{postData.title}</title>
</Head>
{/* Keep the existing code here */}
</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}
// Add this import
import Date from '../../components/date';
export default function Post({ postData }) {
return (
<Layout>
{/* Keep the existing code here */}
{/* Replace {postData.date} with this */}
<Date dateString={postData.date} />
{/* Keep the existing code here */}
</Layout>
);
}如果你访问 https://:3000/posts/pre-rendering,现在应该会看到日期显示为 “January 1, 2020”。
添加 CSS
最后,让我们使用之前添加的 styles/utils.module.css 文件添加一些 CSS。打开 pages/posts/[id].js,然后添加 CSS 文件的导入,并用以下代码替换 Post 组件
// Add this import at the top of the file
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>
);
}如果你访问 https://:3000/posts/pre-rendering,页面现在应该看起来好一些了

干得好!接下来我们将美化索引页,然后就完成了!
这有帮助吗?