Skip to content

制作可重用的导航组件

现在你已经在 Astro 站点的多个页面中编写了相同的 HTML,是时候用可重用的 Astro 组件替换重复的内容了!

¥Now that you have the same HTML written in multiple pages of your Astro site, it’s time to replace that duplicated content with a reusable Astro component!

准备好……

  • 为组件创建一个新文件夹

  • 构建一个 Astro 组件来显示你的导航链接

  • 用新的、可重用的导航组件替换现有的 HTML

新建 src/components/ 文件夹

标题部分 新建 src/components/ 文件夹

¥Create a new src/components/ folder

要保存将生成 HTML 但不会成为你网站上的新页面的 .astro 文件,你需要在项目中创建一个新文件夹:src/components/

¥To hold .astro files that will generate HTML but that will not become new pages on your website, you will need a new folder in your project: src/components/.

¥Create a Navigation component

  1. Create a new file: src/components/Navigation.astro.

  2. Copy your links to navigate between pages from the top of any page and paste them into your new file, Navigation.astro:

    src/components/Navigation.astro
    ---
    ---
    <a href="/">Home</a>
    <a href="/about/">About</a>
    <a href="/blog/">Blog</a>

导入并使用 Navigation.astro

标题部分 导入并使用 Navigation.astro

¥Import and use Navigation.astro

  1. Go back to index.astro and import your new component inside the code fence:

    src/pages/index.astro
    ---
    import Navigation from '../components/Navigation.astro';
    import "../styles/global.css";
    const pageTitle = "Home Page";
    ---
  2. Then below, replace the existing navigation HTML link elements with the new navigation component you just imported:

    src/pages/index.astro
    <a href="/">Home</a>
    <a href="/about/">About</a>
    <a href="/blog/">Blog</a>
    <Navigation />
  3. Check the preview in your browser and notice that it should look exactly the same… and that’s what you want!

你的网站包含与以前相同的 HTML。但现在,这三行代码是由 <Navigation /> 组件提供的。

¥Your site contains the same HTML as it did before. But now, those three lines of code are provided by your <Navigation /> component.

自己尝试一下 - 将导航添加到你网站的其余部分

标题部分 自己尝试一下 - 将导航添加到你网站的其余部分

¥Try it yourself - Add navigation to the rest of your site

使用相同的方法在站点的其他两个页面(about.astroblog.astro)中导入并使用 <Navigation /> 组件。

¥Import and use the <Navigation /> component in the other two pages on your site (about.astro and blog.astro) using the same method.

别忘了

¥Don’t forget to

  • 在组件脚本顶部的代码围栏内添加导入语句。

  • 将现有代码替换为导航组件。

¥Test your knowledge

  1. 当元素在多个页面上重复时,你可以执行此操作:
  1. Astro 组件有:
  1. 当你…时,Astro 组件将自动在你的网站上创建一个新页面。

¥Checklist

¥Resources

Astro 中文网 - 粤ICP备13048890号