使用 Draftjs 的简单撤消和重做按钮

Simple undo and redo button with Draftjs

我正在尝试让一个简单的撤消和重做按钮开始工作。到目前为止,我已经尝试通读 draftjs 网站上的文档,但感觉很晦涩,而且没有关于我正在尝试做的事情的示例。

这是我到目前为止尝试过的,点击撤消它什么也没做。不知道我错过了什么。提前致谢。

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }

  onClick() {
    this.setState({
      editorState: EditorState.undo(editorState)
    })
  }

  render() {
    return (
      <div>
      <button onClick={this.onClick.bind(this)}>undo</button>
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
        </div>
    );
  }
}

ReactDOM.render(
  <MyEditor />,
  document.getElementById('root')
);

这是修复,我需要像这样正确引用编辑状态,然后我根据 Simon 的回答重构:

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }

  onUndo() {
    this.onChange(EditorState.undo(this.state.editorState));
  }

  onRedo() {
    this.onChange(EditorState.redo(this.state.editorState));
  }

  render() {
    return (
      <div>
      <button onClick={this.onUndo.bind(this)}>undo</button>
      <button onClick={this.onRedo.bind(this)}>Redo</button>
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
        </div>
    );
  }
}

ReactDOM.render(
  <MyEditor />,
  document.getElementById('root')
);

你已经找到原因了(你需要正确引用 editorState 变量),但我还是想在路上给你这个:

您应该如下更改 onClick 方法:

onClick() {
  this.setState({
    editorState: EditorState.undo(editorState)
  })
}

onClick() {
  this.onChange(EditorState.undo(this.state.editorState));
}

对于 DraftJS,如果您尝试通过 onChange 以外的方法更改 editorState,通常是 "bad practise"。

如果您对 editorState 进行任何更改,只需在完成后触发 onChange

另外,你知道 Draft JS Plugins 吗?这是 DraftJS 非常有用的插件的精彩集合,还包括 undo/redo 按钮!

https://www.draft-js-plugins.com/

您可以轻松使用选秀团队提供的Undo/Redo插件

check it out please