【问题标题】:How to trigger onchange only when the content changes in draft js editor?仅当草稿js编辑器中的内容发生更改时如何触发onchange?
【发布时间】:2021-01-15 08:51:57
【问题描述】:

draft js 中的 onchange 方法在编辑和选择更改发生时由编辑器执行。但我只想在用户正在写作或内容发生变化而不是焦点或选择时调用触发器 onchange。有什么方法可以比较以前和当前的编辑器状态吗?

【问题讨论】:

    标签: reactjs rich-text-editor draftjs


    【解决方案1】:

    您不能完全这样做,因为 Draft-js 将鼠标的选择状态保持在编辑器状态中,必须触发 onChange,并且您必须更新编辑器状态,但是您检查旧的和新的编辑器状态纯文本并确定是否添加或删除了某些字符

    
    const [editorState,setEditorState]= useState(EditorState.createEmpty());
    
    function onChange(newEditorState: EditorState) {
        
        const currentPlainText = editorState.getCurrentContent().getPlainText();
        const newPlainText = newEditorState.getCurrentContent().getPlainText();
    
        setEditorState(newEditorState);
    
    
        if (currentPlainText.trim() !== newPlainText.trim()) {
    
            /**
             * do what you want knowing that you have different content in the editor
             */
        }
    
    }
    

    【讨论】:

    • 这仅在内容本身发生变化时有效,但在内联样式发生变化时无效
    猜你喜欢
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多