Tauri+React集成EditorJS异常:功能无法使用求助
解决方案:EditorJS 在 Tauri + React 中交互异常与尺寸适配修复
针对你遇到的 EditorJS 仅小范围可交互、点击别处后无法再交互、功能受限的问题,可通过以下步骤修复:
1. 规范 EditorJS 实例生命周期管理
当前代码未正确处理实例的创建与销毁,且缺少工具配置,导致功能受限。修改后的代码如下:
import React, { useRef, useEffect } from 'react'; import { Container, Props } from './styles'; import EditorJS from '@editorjs/editorjs'; const HomePage: React.FC<Props> = ({ pageName, visible }) => { const editorRef = useRef<HTMLDivElement>(null); const editorInstanceRef = useRef<EditorJS | null>(null); // 保存编辑器实例,避免重复创建 useEffect(() => { // 页面隐藏时销毁实例 if (!visible) { editorInstanceRef.current?.destroy(); editorInstanceRef.current = null; return; } // 页面可见且无实例时初始化编辑器 if (editorRef.current && !editorInstanceRef.current) { editorInstanceRef.current = new EditorJS({ holder: editorRef.current, // 配置必要编辑工具,若无此配置编辑器仅基础选中功能 tools: { paragraph: { class: require('@editorjs/paragraph'), inlineToolbar: true }, header: { class: require('@editorjs/header'), config: { levels: [1,2,3], defaultLevel: 2 } } // 可按需添加其他工具(如列表、图片等) } }); } // 组件卸载时清理实例 return () => { editorInstanceRef.current?.destroy(); editorInstanceRef.current = null; }; }, [visible]); // 依赖visible状态,确保页面显隐时正确处理实例 return ( <Container className={`app-container-column ${visible ? '' : 'hide-page'}`}> <h1>Why can I do this?</h1> {/* 给编辑器容器设置明确样式,确保交互区域尺寸正常 */} <div id="editorjs" ref={editorRef} style={{ minHeight: '400px', width: '100%', padding: '1rem', border: '1px solid #eee' }} ></div> <h2>new</h2> </Container> ); }; export default HomePage;
2. 调整 Tauri 窗口配置
在 tauri.conf.json 中修改窗口配置,确保 WebView 事件正常传递:
{ "tauri": { "window": { "focus": true, "webview": { "disableContextMenu": false // 避免拦截编辑器右键交互(若有需要) } } } }
3. 修复容器 CSS 样式
检查 Container 组件的样式,避免设置导致编辑器元素被遮挡的属性:
// 示例 styles.ts 调整 export const Container = styled.div` display: flex; flex-direction: column; gap: 1rem; padding: 2rem; width: 100%; min-height: 100vh; overflow: visible; // 确保编辑器浮动工具条不被截断 `;
4. 补充 EditorJS 依赖
确保安装了核心包及所需工具:
npm install @editorjs/editorjs @editorjs/paragraph @editorjs/header
核心修复逻辑
- 实例管理:用 ref 保存编辑器实例,在页面隐藏或组件卸载时销毁,避免内存泄漏与实例冲突。
- 工具配置:显式声明编辑工具,否则编辑器仅提供基础选中功能。
- 尺寸适配:给编辑器容器设置明确的宽高与内边距,确保交互区域足够。
- 事件传递:调整 Tauri 配置,保证编辑器的交互事件能正常被 WebView 接收。
内容的提问来源于stack exchange,提问作者Sisu
相关产品推荐
相关产品推荐

