【问题标题】:How to push a content state to a current editor state? editorState.push method seems not work for me?如何将内容状态推送到当前编辑器状态? editorState.push 方法似乎对我不起作用?
【发布时间】:2019-07-05 10:33:44
【问题描述】:

存在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变成了全新的东西,就像从text创建一样。 这里有什么错误的用法吗?还是有其他方法可以解决问题?

【问题讨论】:

    标签: draftjs react-draft-wysiwyg


    【解决方案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. 将内容状态、文本转换为块数组; 2.将两个块数组组合在一起; 3. 使用组合数组创建新的内容状态和编辑器状态;

    【讨论】:

    • 谢谢,这完美解决了我的问题:)
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多