页面同时存在可编辑与只读DraftJS编辑器时可编辑实例失焦如何解决
问题根因
DraftJS 中的EditorState是和单个Editor实例绑定的专属状态对象,禁止同时传递给多个Editor组件共用。你在可编辑编辑器中输入触发EditorState更新时,两个绑定了同一状态的编辑器都会触发内部状态同步逻辑,导致可编辑编辑器的焦点被抢占,就会出现持续失焦的问题。
修复方案
只读预览的编辑器不要直接复用可编辑编辑器的EditorState,而是基于可编辑状态的内容,独立创建专属的预览用EditorState即可。
修改后的App.tsx代码
import React, { useMemo } from "react"; import { EditorState } from "draft-js"; import { Editor } from "./Editor"; const App = () => { const [editableState, setEditableState] = React.useState<EditorState>(() => EditorState.createEmpty() ); // 为只读预览创建独立的EditorState,仅同步内容,不共享状态实例 const readOnlyState = useMemo(() => { return EditorState.createWithContent(editableState.getCurrentContent()); }, [editableState.getCurrentContent()]); return ( <> <h3>Editor</h3> <Editor state={editableState} onChange={(state) => setEditableState(state)} /> <h3>Result</h3> <Editor state={readOnlyState} readOnly onChange={() => null} /> </> ); }; export default App;
内容的提问来源于stack exchange,提问作者JayK
相关产品推荐
相关产品推荐

