无需 React 的使用方法(纯 JavaScript)
BlockNote 主要设计为 React 应用中快速且简易的块级编辑器,但也可以在纯 JavaScript 应用中使用。不过,这需要你自己编写 UI 元素。
⚠️
我们建议在 React 中使用 BlockNote,这样你可以利用内置的 UI 组件。本文档将说明如何在不使用 React 的情况下使用 BlockNote, 并编写你自己的组件,但不推荐这样做,因为你将失去 BlockNote 出色的开箱即用体验。
使用 NPM 安装
要仅安装 BlockNote 的纯 JS 部分,请使用 NPM (opens in a new tab) 运行:
npm install @blocknote/core
创建编辑器
以下是创建一个新的 BlockNote 编辑器的方法:
import { BlockNoteEditor } from "@blocknote/core";
const editor = BlockNoteEditor.create();
editor.mount(document.getElementById("root")); // 挂载编辑器的元素
现在,你的页面上已经有一个基础的 BlockNote 实例了。但它缺少一些菜单和其他 UI 元素。
创建你自己的 UI 元素
因为你无法使用内置的 React UI 组件,所以需要创建并注册你自己的 UI 元素。
虽然你可以自由决定如何渲染这些元素,BlockNote 提供了用于更新元素可见性、位置和状态的方法:
type UIElement =
| "formattingToolbar"
| "linkToolbar"
| "filePanel"
| "sideMenu"
| "suggestionMenu"
| "tableHandles"
const uiElement: UIElement = ...;
editor[uiElement].onUpdate((uiElementState: ...) => {
...;
})
接下来,来看一个如何向编辑器添加侧边菜单的示例:
import { BlockNoteEditor } from "@blocknote/core";
const editor = BlockNoteEditor.create({
element: document.getElementById("root")!,
});
export function createButton(text: string, onClick?: () => void) {
const element = document.createElement("a");
element.href = "#";
element.text = text;
element.style.margin = "10px";
if (onClick) {
element.addEventListener("click", (e) => {
onClick();
e.preventDefault();
});
}
return element;
}
let element: HTMLElement;
editor.sideMenu.onUpdate((sideMenuState) => {
if (!element) {
element = document.createElement("div");
element.style.background = "gray";
element.style.position = "absolute";
element.style.padding = "10px";
element.style.opacity = "0.8";
const addBtn = createButton("+", () => {
editor.sideMenu.addBlock();
});
element.appendChild(addBtn);
const dragBtn = createButton("::", () => {});
dragBtn.addEventListener("dragstart", editor.sideMenu.blockDragStart);
dragBtn.addEventListener("dragend", editor.sideMenu.blockDragEnd);
dragBtn.draggable = true;
element.style.display = "none";
element.appendChild(dragBtn);
document.getElementById("root")!.appendChild(element);
}
if (sideMenuState.show) {
element.style.display = "block";
element.style.top = sideMenuState.referencePos.top + "px";
element.style.left =
sideMenuState.referencePos.x - element.offsetWidth + "px";
} else {
element.style.display = "none";
}
});