如何在draft-js中基于SelectionState创建带格式的新EditorState
Draft.js 保留格式提取选中内容实现方案
你原有的实现只提取了纯文本内容,没有保留块样式、内联样式、实体等元信息,所以会丢失格式。可以直接用Draft.js官方提供的片段提取API实现带格式的选中内容提取:
完整实现代码
import { EditorState, ContentState, convertToRaw } from 'draft-js'; /** * 提取选中范围的完整ContentState(保留所有格式) */ export const getSelectedContentState = (editorState: EditorState): ContentState => { const selection = editorState.getSelection(); // 可选:处理没有选中内容的空选场景 if (selection.isCollapsed()) { return ContentState.createFromText(''); } const currentContent = editorState.getCurrentContent(); // 获取选中范围的完整块片段,自带所有格式、实体信息 const selectedBlocks = currentContent.getFragmentForRange(selection); // 用选中的块生成新的ContentState return ContentState.createFromBlockArray(selectedBlocks.toArray()); }; /** * 直接获取选中内容的可持久化Raw格式 */ export const getSelectedRaw = (editorState: EditorState): Record<string, any> => { return convertToRaw(getSelectedContentState(editorState)); }; /** * 直接获取选中内容对应的新EditorState */ export const getSelectedEditorState = (editorState: EditorState): EditorState => { return EditorState.createWithContent(getSelectedContentState(editorState)); };
核心说明
ContentState.getFragmentForRange是Draft.js原生提供的API,传入SelectionState就能直接返回选中范围的完整块集合,会自动处理单块部分选中、多块跨选的场景,保留所有内联样式、块类型、链接/媒体等实体信息- 生成的新ContentState可以直接用
convertToRaw序列化为可持久化的JSON结构,后续恢复时用convertFromRaw解析即可还原所有格式 - 如果要做剪切操作,可以配合
Modifier.removeRange删除原编辑器中的选中内容,和提取操作结合即可实现带格式的剪切功能
内容的提问来源于stack exchange,提问作者user3396980
相关产品推荐
相关产品推荐

