我正在尝试让一个简单的撤消和重做按钮开始工作。到目前为止,我已经尝试通读 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')
);
最佳答案
你已经找到原因了(你需要正确引用 editorState 变量),但我仍然想在途中给你这个:
您应该按如下方式更改您的onClick
方法:
onClick() {
this.setState({
editorState: EditorState.undo(editorState)
})
}
到
onClick() {
this.onChange(EditorState.undo(this.state.editorState));
}
对于 DraftJS,如果您尝试通过 onChange
以外的方法更改 editorState 通常是“不好的做法”。
如果您对 editorState 进行任何更改,只需在完成后触发 onChange
。
另外,你知道 Draft JS Plugins 吗?这是 DraftJS 非常有用的插件的精彩集合,还包括撤消/重做按钮!
关于javascript - 使用 Draftjs 的简单撤消和重做按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45237941/