跳到内容

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,你应该能看到日期显示为 “2020年1月1日”

添加 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,页面现在看起来应该更好一些了

Example

做得好!接下来我们将优化首页,然后就完成了!

你已完成章节34

下一步

35: 优化首页