Skip to main content

一篇 MDX 博客示例:像写 Markdown 一样写 React

这是一个 MDX 博客示例:你可以像写 Markdown 一样写文章,同时在正文里直接使用 React 组件。

你能用 MDX 做什么?

一句话理解

MDX = Markdown + JSX。你可以在 Markdown 里直接写组件。

1) Tabs:把同一段内容分成多个视角

  • 写作体验仍然是 Markdown
  • 需要交互/组件时直接插入 JSX

2) 代码块:高亮 / 可选组件化

下面是普通 Markdown 代码块:

export function hello(name) {
return `Hello, ${name}!`;
}

1) Counter:最小交互示例

你可以在页面里直接点击按钮,状态会实时更新。

Live Editor
function Counter() {
  const [n, setN] = React.useState(0);

  return (
    <div style={{
      display: 'flex',
      gap: 12,
      alignItems: 'center',
      fontFamily: 'system-ui, -apple-system, Segoe UI, Roboto, sans-serif'
    }}>
      <button onClick={() => setN(n - 1)} style={{padding: '6px 10px'}}></button>
      <b style={{minWidth: 24, textAlign: 'center'}}>{n}</b>
      <button onClick={() => setN(n + 1)} style={{padding: '6px 10px'}}>+</button>
      <span style={{opacity: 0.7}}>(点击试试)</span>
    </div>
  );
}
Result
Loading...

2) 颜色选择器

Live Editor
function ColorPreview() {
  const [color, setColor] = React.useState('#2563eb');

  return (
    <div style={{display: 'flex', gap: 16, alignItems: 'center'}}>
      <div>
        <div style={{fontSize: 12, opacity: 0.75, marginBottom: 6}}>输入颜色(hex):</div>
        <input
          value={color}
          onChange={(e) => setColor(e.target.value)}
          placeholder="#2563eb"
          style={{
            padding: '8px 10px',
            border: '1px solid #e5e7eb',
            borderRadius: 8,
            width: 140
          }}
        />
      </div>

      <div style={{
        width: 56,
        height: 56,
        borderRadius: 12,
        border: '1px solid #e5e7eb',
        background: color
      }} />

      <div style={{fontSize: 12, opacity: 0.75}}>
        当前值:<code>{color}</code>
      </div>
    </div>
  );
}
Result
Loading...