MDX 组件的使用与参数传递

106 阅读1分钟

引言

MDX 支持在文档中直接使用 React 组件,并通过属性(props)进行参数传递,实现内容的高度可复用与个性化。

基本用法

  • .mdx 文件中插入组件标签,并传递属性:
    <Alert type="info" message="这是一个信息提示!" />
    
  • 组件需通过 import 语句引入,或在渲染时通过 components 属性注册。

典型场景

  • 显示不同类型的提示、警告、成功等消息
  • 渲染可配置的交互式演示组件
  • 复用页面片段,提升内容一致性

示例代码

import Alert from './Alert.jsx'

# 组件参数传递示例

<Alert type="success" message="操作成功!" />
<Alert type="error" message="发生错误,请重试。" />
// Alert.jsx
import React from 'react';
export default function Alert({ type, message }) {
  const color = type === 'success' ? '#52c41a' : type === 'error' ? '#ff4d4f' : '#1890ff';
  return <div style={{ borderLeft: `4px solid ${color}`, padding: '8px 16px', margin: '8px 0', background: '#f6f8fa' }}>{message}</div>;
}

注意事项

  • 组件名需大写字母开头,符合 React 规范
  • 属性名建议使用小驼峰命名(如 showTitle
  • 组件需在渲染环境中注册(如通过 components 属性传递)
  • 复杂交互建议将逻辑封装在组件内部

总结

通过组件与参数传递,MDX 实现了内容与交互的高度解耦和复用,是构建高质量文档和教程的关键能力。