docs/installation/rsc.cn.mdx
本指南演示如何在React Server Components (RSC)中使用Plate进行静态内容生成或服务端数据处理等任务。Plate的核心设计是服务端安全的,允许您在没有浏览器环境的情况下处理编辑器内容。
<Callout type="warning" title="关键RSC限制"> 在RSC中使用Plate时,**禁止**从任何`platejs*`包的`/react`子路径导入。始终使用基础导入(例如使用`@platejs/basic-nodes`而非`@platejs/basic-nodes/react`)。这意味着您不能使用platejs/react中的createPlateEditor。请改用platejs中的createSlateEditor。
</Callout>
安装核心Plate包及您需要的特定插件包。
npm install platejs @platejs/basic-nodes
在RSC环境中,您需要使用platejs中的createSlateEditor来初始化编辑器实例。该函数不依赖React钩子或客户端特定代码。
以下示例展示如何设置带有各种插件的编辑器,类似于服务端示例:
import { createSlateEditor } from 'platejs';
import { AutoformatPlugin } from '@platejs/autoformat';
import { BaseTextAlignPlugin } from '@platejs/basic-styles';
import {
BaseBoldPlugin,
BaseCodePlugin,
BaseItalicPlugin,
BaseBlockquotePlugin,
BaseH1Plugin,
BaseH2Plugin,
BaseH3Plugin,
} from '@platejs/basic-nodes';
import { MarkdownPlugin, remarkMdx } from '@platejs/markdown';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
// 示例初始值
const initialValue = [
{ type: 'h1', children: [{ text: '服务端生成文档' }] },
{ type: 'p', children: [{ text: '此内容在服务端处理完成。' }] },
{ type: 'blockquote', children: [{ text: '这是一段引用。' }] },
{ type: 'p', children: [{ text: '这是加粗文本。', bold: true }] },
];
// 创建编辑器实例
const editor = createSlateEditor({
plugins: [
// 块级插件
BaseH1Plugin,
BaseH2Plugin,
BaseH3Plugin,
BaseBlockquotePlugin,
BaseTextAlignPlugin,
// ... 按需添加更多元素插件
// 标记插件
BaseBoldPlugin,
BaseItalicPlugin,
BaseCodePlugin,
// ... 添加更多标记插件
// 功能插件
AutoformatPlugin,
MarkdownPlugin.configure({ // 序列化示例
options: {
remarkPlugins: [remarkMath, remarkGfm, remarkMdx],
},
}),
// ... 添加其他功能插件
],
value: initialValue, // 设置初始内容
});
// 您现在可以使用editor.children, editor.api, editor.tf等
// 例如获取文本内容:
const textContent = editor.api.string([]);
// console.debug('文本内容:', textContent);
// 或序列化为Markdown:
const markdown = editor.api.markdown.serialize();
// console.debug('Markdown输出:', markdown);
// 编辑器实例可用于各种服务端任务
// 完整的使用示例请参阅/docs/examples/server-side页面
Plate在RSC中的主要用例是程序化内容操作:
editor.api: 访问各种查询编辑器状态的实用函数。例如:
editor.api.nodes({ at: [], match }): 查找特定节点editor.api.string([]): 提取文本内容editor.tf: 使用转换函数修改编辑器内容。例如:
editor.tf.insertNodes(nodes, opts): 插入新节点editor.tf.removeNodes(opts): 删除节点editor.tf.setNodes(props, opts): 更新现有节点属性editor.tf.normalize({ force: true }): 规范化编辑器在RSC环境中配置好Plate后,您现在可以:
PlateStatic