docs/(guides)/editor-methods.cn.mdx
本指南涵盖了Plate编辑器实例上可用的各种方法。
访问编辑器实例的方式取决于您需要的上下文。
使用以下钩子之一:
useEditorRef: 永不重新渲染。useEditorSelector: 仅当特定编辑器属性变化时重新渲染。useEditorState: 每次变化都重新渲染。import { useEditorRef, useEditorSelector, useEditorState } from 'platejs/react';
const MyComponent = () => {
const editor = useEditorRef();
const hasSelection = useEditorSelector((editor) => !!editor.selection, []);
const editorState = useEditorState();
// ...
};
useEditorRef总是足以在回调中访问编辑器。useEditorRef不会导致组件重新渲染,因此是性能最佳的选择。const hasSelection = useEditorSelector((editor) => !!editor.selection, []);useEditorSelector访问相关属性。===进行比较。通常这意味着返回原始值(数字、字符串或布尔值)。useEditorSelector提供自定义的equalityFn选项来处理===不适用的情况。useEditorState会导致组件在用户每次按键或改变选择时重新渲染。要在Plate组件外部访问编辑器或处理多个编辑器,使用PlateController组件:
import { PlateController } from 'platejs/react';
const App = () => (
<PlateController>
<Toolbar />
<MyEditor />
</PlateController>
);
const Toolbar = () => {
const editor = useEditorState();
const isMounted = useEditorMounted();
// 在此使用编辑器方法
};
PlateController管理活动编辑器:
Plate上的primary={false}覆盖)。PlateController内部的钩子如useEditorRef和useEditorSelector会与活动编辑器交互。若无活动编辑器,它们会返回一个回退编辑器,该编辑器:
回退编辑器场景:
Plate组件。Plate组件都标记为非主要。PlateContent挂载过程中。可使用useEditorMounted检查是否有编辑器已挂载:
const Toolbar = () => {
const editor = useEditorState();
const isMounted = useEditorMounted();
if (!isMounted) {
return <div>编辑器未就绪</div>;
}
return <div></div>;
};
也可通过editor.meta.isFallback检查是否为回退实例。
查找节点的路径。默认为findNodePath(遍历)。被withPlate覆盖为使用ReactEditor.findPath(记忆化)。
const path = editor.findPath(node);
获取编辑器的类型化API:
const api = editor.getApi(TablePlugin);
api.api.create.tableCell(); // 类型安全的API方法
获取编辑器的类型化转换方法:
const tf = editor.getTransforms(TablePlugin);
tf.insert.tableRow(); // 类型安全的转换方法
通过键或基础插件获取编辑器插件实例:
const codeBlockPlugin = editor.getPlugin(CodeBlockPlugin);
const headingPlugin = editor.getPlugin({ key: KEYS.heading });
获取与插件关联的节点类型:
const paragraphType = editor.getType(KEYS.p);
获取插件的特定选项值:
const search = editor.getOption(FindReplacePlugin, 'search');
要订阅选项变化,可使用usePluginOption或usePluginOptions钩子。
获取插件的所有选项:
const linkOptions = editor.getOptions(LinkPlugin);
设置插件的特定选项值:
editor.setOption(FindReplacePlugin, 'search', 'hello');
设置插件的多个选项:
editor.setOptions(FindReplacePlugin, {
search: 'hello',
caseSensitive: true,
});
也可使用Immer函数更新选项:
editor.setOptions(FindReplacePlugin, (draft) => {
draft.search = 'hello';
draft.caseSensitive = true;
});
获取插件的zustand-x选项存储:
const store = editor.getOptionsStore(FindReplacePlugin);