制作可重用的导航组件
现在你已经在 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!
Get ready to…
-
为组件创建一个新文件夹
-
构建一个 Astro 组件来显示你的导航链接
-
用新的、可重用的导航组件替换现有的 HTML
新建 src/components/
文件夹
Section titled 新建 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/
.
创建导航组件
Section titled 创建导航组件¥Create a Navigation component
-
Create a new file:
src/components/Navigation.astro
. -
Copy your links to navigate between pages from the top of any page and paste them into your new file,
Navigation.astro
:
导入并使用 Navigation.astro
Section titled 导入并使用 Navigation.astro¥Import and use Navigation.astro
-
Go back to
index.astro
and import your new component inside the code fence: -
Then below, replace the existing navigation HTML link elements with the new navigation component you just imported:
-
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.
自己尝试一下 - 将导航添加到你网站的其余部分
Section titled 自己尝试一下 - 将导航添加到你网站的其余部分¥Try it yourself - Add navigation to the rest of your site
使用相同的方法在站点的其他两个页面(about.astro
和 blog.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
-
在组件脚本顶部的代码围栏内添加导入语句。
-
将现有代码替换为导航组件。
测试你的知识
Section titled 测试你的知识¥Test your knowledge
- 当元素在多个页面上重复时,你可以执行此操作:
- Astro 组件有:
- 当你…时,Astro 组件将自动在你的网站上创建一个新页面。
¥Checklist
¥Resources
-
重构 external