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

Lea*_*cim 11 reactjs draftjs

我在Draft-js上看到的所有演示(由Facebook构建,基于React)都没有显示如何在提交后清除输入字段.例如,请参阅从awesome-draft-js链接到的代码笔,其中您提交的值在提交后仍保留在输入字段中.api中似乎没有任何 功能可以实现.我所做的就是在按钮提交上创建一个新的空状态,就像这样

onSubmit(){
this.setState({
   editorState: EditorState.createEmpty(),
})
}
Run Code Online (Sandbox Code Playgroud)

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

  this.state = {
    editorState: EditorState.createEmpty(),
  };
Run Code Online (Sandbox Code Playgroud)

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

Sah*_*hil 22

这是推荐使用EditorState.createEmpty()来清除编辑器的状态-你应该只在初始化使用createEmpty.

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

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

const editorState = EditorState.push(this.state.editorState, ContentState.createFromText(''));
this.setState({ editorState });
Run Code Online (Sandbox Code Playgroud)

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

  • 您可能还想传递第三个参数。`EditorState.push(editorState, ContentState.createFromText(''), 'remove-range')` (3认同)

bre*_*tex 8

@Vikram Mevasiya 的解决方案无法正确清除阻止列表样式

@Sahil 的解决方案使光标在下一个输入上混乱

我发现这是唯一有效的解决方案:

// https://github.com/jpuri/draftjs-utils/blob/master/js/block.js
const removeSelectedBlocksStyle = (editorState)  => {
    const newContentState = RichUtils.tryToRemoveBlockStyle(editorState);
    if (newContentState) {
        return EditorState.push(editorState, newContentState, 'change-block-type');
    }
    return editorState;
}

// https://github.com/jpuri/draftjs-utils/blob/master/js/block.js
export const getResetEditorState = (editorState) => {
    const blocks = editorState
        .getCurrentContent()
        .getBlockMap()
        .toList();
    const updatedSelection = editorState.getSelection().merge({
        anchorKey: blocks.first().get('key'),
        anchorOffset: 0,
        focusKey: blocks.last().get('key'),
        focusOffset: blocks.last().getLength(),
    });
    const newContentState = Modifier.removeRange(
        editorState.getCurrentContent(),
        updatedSelection,
        'forward'
    );

    const newState = EditorState.push(editorState, newContentState, 'remove-range');
    return removeSelectedBlocksStyle(newState)
}
Run Code Online (Sandbox Code Playgroud)

它是https://github.com/jpuri/draftjs-utils提供的两个辅助函数的组合。不想npm install为此提供整个包裹。它重置光标状态但保留阻止列表样式。这是通过应用程序删除的,removeSelectedBlocksStyle() 我简直不敢相信如此成熟的库如何不提供单行重置功能。