Skip to content

React 组件渲染使用指南

本文档说明如何在 VitePress 文档中渲染 React 组件。

快速开始

1. 创建 React 组件示例

demos/ 目录下创建你的 React 组件:

tsx
// demos/my-component.tsx
import React, { useState } from 'react'

export default function MyComponentDemo() {
  const [count, setCount] = useState(0)

  return (
    <button onClick={() => setCount(count + 1)}>
      点击次数: {count}
    </button>
  )
}

2. 在 Markdown 中使用

在你的 .md 文件中添加:

vue
<script setup>
import MyDemo from '../../demos/my-component.tsx'
import { defineComponent, h, onMounted, onBeforeUnmount } from 'vue'
import { createRoot } from 'react-dom/client'
import React from 'react'

const ReactDemo = defineComponent({
  name: 'ReactDemo',
  setup() {
    let root = null
    let container = null

    onMounted(() => {
      container = document.createElement('div')
      const target = document.querySelector('#my-demo')
      if (target) {
        target.appendChild(container)
        root = createRoot(container)
        root.render(React.createElement(MyDemo))
      }
    })

    onBeforeUnmount(() => {
      if (root) {
        root.unmount()
      }
      if (container && container.parentNode) {
        container.parentNode.removeChild(container)
      }
    })

    return () => h('div', { id: 'my-demo' })
  }
})
</script>

<ReactDemo />

已有示例

  • demos/button-basic.tsx - Button 组件示例
  • demos/tabbar-basic.tsx - Tabbar 组件示例
  • demos/input-basic.tsx - Input 组件示例

注意事项

  1. React 组件文件必须放在 demos/ 目录下
  2. 每个组件需要 default export
  3. 组件会自动支持热更新
  4. 可以使用 React Hooks
  5. 可以导入 @xcloud/ui-* 包中的组件

样式

React 组件会继承文档的主题样式,包括深色模式。你可以:

  • 使用 CSS-in-JS(如示例)
  • 使用 CSS 变量(var(--vp-c-*))
  • 导入组件库的样式文件

调试

如果组件没有渲染:

  1. 检查浏览器控制台是否有错误
  2. 确认组件文件路径正确
  3. 确认组件有 default export
  4. 检查 id 是否唯一

最佳实践

  • 保持示例组件简单、独立
  • 使用有意义的命名
  • 添加必要的交互来展示功能
  • 考虑移动端和桌面端的显示效果

基于 MIT 许可发布