这篇文章演示了所有可在 MDX 博客文章中使用的交互组件。 滚动页面时右侧目录会高亮当前章节,顶部有阅读进度条,代码块可以一键复制。
提示框(Callout)
ℹ️
什么是 MDX?
MDX 是 Markdown 的超集,允许在文章中直接嵌入 JSX 组件。
在 Astro 中,使用 @astrojs/mdx 集成即可在内容文件中使用 React 组件。
💡
提示
所有交互组件都支持深色模式,跟随站点主题自动切换。
⚠️
注意事项
交互组件依赖 React,使用 client:visible 或 client:load 指令按需加载,不影响静态内容的性能。
🚨
破坏性更改
若升级主要版本,请先阅读迁移指南,避免 Breaking Change 造成的问题。
步骤引导(Steps)
运行 npm install 安装所有项目依赖。
编辑 src/config/site.ts,填写站点名称、作者、链接等。
在 src/content/blog/ 创建 .md 或 .mdx 文件。
推送到 GitHub,在 Cloudflare Dashboard 中连接仓库并部署。
标签页(Tabs)
npm install astro @astrojs/react @astrojs/tailwind
pnpm add astro @astrojs/react @astrojs/tailwind
yarn add astro @astrojs/react @astrojs/tailwind
数据可视化
柱状图
折线图(多系列)
React
Vue
Svelte
饼图
- TypeScript45%
- React25%
- Node.js15%
- Rust10%
- 其他5%
交互 Demo
计数器
0
点击次数
开关组件
深色模式
邮件通知
自动保存
颜色选择器
#6366f1算法可视化
冒泡排序可视化 —— 点击「冒泡排序」观察排序过程,随机重置后再次尝试。
冒泡排序
代码示例(带复制按钮)
鼠标悬停在代码块上即可看到右上角的复制按钮。
// 使用 Astro Content Collections 获取博客文章
import { getCollection } from 'astro:content';
const posts = await getCollection('blog', ({ data }) => {
return !data.draft && data.date <= new Date();
});
// 按日期降序排列
posts.sort((a, b) => b.data.date.getTime() - a.data.date.getTime());
# 本地开发
npm run dev
# 构建生产版本
npm run build
# 预览构建结果
npm run preview
在你的文章中使用
在任意 .mdx 文件顶部导入需要的组件:
import { Callout } from '@/components/mdx/Callout';
import { BarChart } from '@/components/mdx/Chart';
import { Steps, Step } from '@/components/mdx/Steps';
import { Tabs, TabItem } from '@/components/mdx/Tabs';
import { Counter } from '@/components/mdx/InteractiveDemo';
import DemoBox from '@/components/mdx/DemoBox.astro';
<Callout type="tip">这是一个提示!</Callout>
<Steps client:visible>
<Step title="第一步">描述内容...</Step>
<Step title="第二步">描述内容...</Step>
</Steps>
<Tabs client:visible>
<TabItem label="选项一">内容A</TabItem>
<TabItem label="选项二">内容B</TabItem>
</Tabs>
<BarChart client:visible title="我的数据" data={[...]} />
<DemoBox title="计数器">
<Counter client:load />
</DemoBox>
📝
性能说明
所有交互组件使用 client:visible 指令——仅在组件进入视口时才加载 JS,
确保文章首屏加载时间不受影响。纯展示组件(如 Callout、Steps)无需任何 JS。