如何清除Draft-js中的输入字段

问题描述 投票:11回答:2

我在Draft-js上看到的所有演示(由Facebook构建,基于React)都没有显示如何在提交后清除输入字段。例如,请参阅此code pen linked to from awesome-draft-js,其中您提交的值在提交后仍保留在输入字段中。似乎没有function in the api可以做到这一点。我所做的就是在按钮提交上创建一个新的空状态,就像这样

onSubmit(){
this.setState({
   editorState: EditorState.createEmpty(),
})
}

但是,因为我在编译器加载时在构造函数中创建一个空状态

  this.state = {
    editorState: EditorState.createEmpty(),
  };

我担心我可能不会以正确的方式执行此操作,即先前的状态对象可能会成为内存泄漏。问题:在上述情况下重置状态的预期方式是什么(即按钮提交)

reactjs draftjs
2个回答
21
投票

不建议使用EditorState.createEmpty()来清除编辑器的状态 - 您应该只在初始化时使用createEmpty。

重置编辑器内容的正确方法:

import { EditorState, ContentState } from 'draft-js';

const editorState = EditorState.push(this.state.editorState, ContentState.createFromText(''));
this.setState({ editorState });

@source:https://github.com/draft-js-plugins/draft-js-plugins/blob/master/FAQ.md


0
投票

试试这个

    let editorState = this.state.editorState
    let contentState = editorState.getCurrentContent()
    const firstBlock = contentState.getFirstBlock()
    const lastBlock = contentState.getLastBlock()
    const allSelected = new SelectionState({
        anchorKey: firstBlock.getKey(),
        anchorOffset: 1,
        focusKey: lastBlock.getKey(),
        focusOffset: lastBlock.getLength(),
        hasFocus: true
    })
    contentState = Modifier.removeRange(contentState, allSelected, 'backward')
    editorState = EditorState.push(editorState, contentState, 'remove-range')
    editorState = EditorState.forceSelection(contentState, contentState.getSelectionAfter())
    this.setState({editorState})
© www.soinside.com 2019 - 2024. All rights reserved.