React 与 Next.js

在 React 生命周期中安全挂载独立编辑器树。

让文档进入你的工作流

React 接入

SDK 自己创建 React Root。宿主提供 DOM 容器即可,不要往同一容器渲染其他 React children。

EditorHost.tsx
"use client";

import { createEditor } from "@musecanto/editor-kit";
import { useEffect, useRef } from "react";

export function EditorHost({ documentId }: { documentId: string }) {
  const hostRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const host = hostRef.current;
    if (!host) return;
    // 隔离 StrictMode 重放与 SDK 异步卸载。
    const target = document.createElement("div");
    target.style.height = "100%";
    host.append(target);
    const instance = createEditor({
      el: target,
      documentId,
      content: "<p>开始书写。</p>",
      ui: { locale: "zh" },
      onCreate(editor) {
        editor.focus();
      },
    });
    return () => {
      instance.destroy();
      target.remove();
    };
  }, [documentId]);
  return <div ref={hostRef} style={{ height: 640 }} />;
}

在全局入口导入 @musecanto/editor-kit/style.css。

Next.js App Router

挂载组件标记 "use client",只在 effect 中调用 createEditor()。遇到浏览器依赖的服务端求值问题,可在客户端边界动态导入:

EditorClient.tsx
"use client";
import dynamic from "next/dynamic";

export const EditorClient = dynamic(
  () => import("./EditorHost").then((mod) => mod.EditorHost),
  { ssr: false, loading: () => <p>正在准备编辑器…</p> },
);

ssr: false 放在 Client Component 中,不直接放进 Server Component。

next.config.ts
import type { NextConfig } from "next";
const config: NextConfig = {
  transpilePackages: ["@musecanto/editor-kit"],
};
export default config;

在 MDX 中嵌入

本文档站把编辑器封装为客户端组件 EditorExample,注册到 Fumadocs MDX 组件表。文档作者不需要管理副作用。

<EditorExample preset="minimal" />
<EditorExample preset="structured" inspect />
<EditorExample preset="welcome" readOnly />

这些是文档站示例组件 props,不是 SDK 的 EditorOptions。

正在准备编辑器…

生命周期注意事项

  • 卸载时执行 destroy();不要复用已经销毁的句柄。
  • 在 onCreate 访问就绪实例,不依赖创建后的同步读取。
  • SDK 为每次挂载创建独立内部节点,destroy 可在 StrictMode 清理中安全调用。
  • 切换文档清理旧订阅,避免旧回调写入新文档。
  • 本地 link 调试保持 React / React DOM 单实例。

本页目录

继续探索编辑器 Playground试写并查看文档输出在 GitHub 查看源码问题反馈与参与贡献

示例使用私有 SDK。
你的内容与存储,由你掌控。