draftjs - 如何将内容状态推送到当前编辑器状态?editorState.push 方法似乎对我不起作用?
问题描述
存在 textEditor 需要插入一些纯文本内容,我尝试使用 EditorState.push 方法,我认为它适用于这种情况。我尝试这样的事情:
const { ContentState: { createFromText }, EditorState: { createWithContent, push }} = DraftJS;
export const pushTextToCurrentEditorState = (text, editorState) => {
const textContentState = createFromText(text);
const newEditorState = push(editorState, textContentState, 'insert-characters');
// debugger;
console.log(editorStateToJSON(editorState))
console.log(editorStateToJSON(newEditorState))
return JSON.parse(editorStateToJSON(newEditorState));
}
结果newEditorState
不是合并状态,而是替换了一个,老的editorState错过了,newEditorState
变成了全新的东西,就像create from the text
. 这里有什么错误的用法吗?还是有其他方法可以解决问题?
解决方案
我厌倦了一种复杂的方式,但解决了这个问题。代码在这里:
export const pushTextToCurrentEditorState = (text, editorState) => {
const textContentState = createFromText(text);
const textContentBlocksArr = textContentState.getBlocksAsArray();
const currentBlocksArr = editorState.getCurrentContent().getBlocksAsArray();
const newBlocksArr = currentBlocksArr.concat(textContentBlocksArr);
const newContentState = createFromBlockArray(newBlocksArr);
const newEditorState = createWithContent(newContentState);
return JSON.parse(editorStateToJSON(newEditorState));
}
方式:1.将内容状态,文本,转换为blocks数组;2. 将两个块数组组合在一起;3. 使用组合数组创建新的内容状态和编辑器状态;
推荐阅读
- reactjs - IDToken 为 react-native-google-signin 返回 null
- clang - 如何匹配来自 cxxMethodDecl 节点的所有返回 stmt
- r - networkD3:如何在没有输出的情况下将桑基图中的颜色分配给节点
- html - HTML 网格在元素之间有很大的空间
- r - 构面网格标题和标签
- graphics - 示例需要在 TeX 中使用 tikz 包进行 for 循环
- r - tidyverse : 连续出现零
- python - Openvino-opencv videocapture 异常行为
- php - PHP 日期问题 - 获取正确的周数
- qt - 将 QPixmap 设置为 Qlabel 会导致分段错误和应用程序崩溃