2

存在 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. 这里有什么错误的用法吗?还是有其他方法可以解决问题?

4

1 回答 1

1

我厌倦了一种复杂的方式,但解决了这个问题。代码在这里:

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. 使用组合数组创建新的内容状态和编辑器状态;

于 2019-07-08T06:42:30.710 回答