| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- import React from 'react';
- import { useCreateBlockNote } from '@blocknote/react';
- import { BlockNoteView } from '@blocknote/mantine';
- import { BlockNoteSchema, createHeadingBlockSpec } from "@blocknote/core";
- import { zh, en } from "@blocknote/core/locales";
- import '@blocknote/mantine/style.css';
- import '@blocknote/core/fonts/inter.css';
- import { uploadFile } from '@/api/common.js'
- // 正确导入需要的组件
- import { ColumnBlock, ColumnListBlock, withMultiColumn, multiColumnSchema} from "@blocknote/xl-multi-column"
- const BlockNoteReact = ({ modelValue, onUpdateModelValue, editable = true, currentLang = 'zh' }) => {
- let isEditable = editable;
- //currentLang变化时重新创建editor实例
- React.useEffect(() => {
- }, [currentLang]);
- // 创建带有多列支持的 schema
- // const schema = BlockNoteSchema.create({
- // blockSpecs: {
- // },
- // });
- // 在React组件内部使用Hook
- const editor = useCreateBlockNote({
- // 正确的方式:创建扩展的schema
- //schema, // 使用扩展后的 schema
- // schema: BlockNoteSchema.create().extend({
- // blockSpecs: {
- // heading: createHeadingBlockSpec({
- // column: ColumnBlock,
- // columnList: ColumnListBlock,
- // }),
- // // 添加多列相关的块类型
-
- // // column: ColumnBlock,
- // // columnList: ColumnListBlock
- // }
- // }),
- id: "blocknote-react-editor",
- dictionary: currentLang === 'en' ? en : zh,
- initialContent: modelValue || undefined,
- iseditable : false,
- autofocus: false, // 默认 false,true 开启自动聚焦
- // 3. 允许使用的块类型(限制编辑器功能)
- // allowedBlockTypes: [
- // "paragraph", // 普通段落
- // "heading", // 标题
- // "list", // 列表(有序/无序)
- // "image", // 图片
- // "quote", // 引用
- // ],
- uploadFile: async (file) => {
- // 上传文件到服务器
- const formData = new FormData();
- formData.append('file', file);
- const response = await uploadFile('/upload', formData);
- console.log('上传响应:', response);
- const data = await response.json();
- return data.url; // 返回图片 URL
- },
- // placeholder: "请输入内容(支持块级编辑、格式设置)"
- });
- editor.onMount(() => {
- console.log('BlockNote 编辑器已挂载(React 版)', editor);
- });
- // 监听编辑器内容变化
- React.useEffect(() => {
- const unsubscribe = editor.onChange(async() => {
- const html = await editor.blocksToFullHTML(editor.document);
- // onUpdateModelValue(editor.document);
- onUpdateModelValue(editor.document,html);
- });
- return unsubscribe;
- }, [editor, onUpdateModelValue]);
- // 监听外部值变化
- React.useEffect(() => {
- if (modelValue && JSON.stringify(modelValue) !== JSON.stringify(editor.document)) {
- editor.replaceBlocks(editor.document, modelValue);
- }
- }, [modelValue, editor]);
- return (
- <BlockNoteView
- editor={editor}
- key={editor.id}
- editable={isEditable}
- />
- );
- };
- export default BlockNoteReact;
|