You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React-Quill按钮点击实现撤销(undo)与重做(redo)的方法

我之前也碰到过一模一样的问题!核心原因其实很简单:手动调用Quill的history.undo()/redo()时,编辑器没有获得焦点,导致ReactQuill的内部状态和Quill实例的编辑上下文没同步——而Ctrl+Z这类快捷键是Quill原生绑定的,触发时自动确保了编辑器处于焦点状态,所以一切正常。

给你几个可行的解决方案:

  • 先聚焦编辑器再执行历史操作
    在调用undo/redo之前,先让Quill实例获得焦点,这样操作就能正确关联编辑状态,不会只出现光标移动却不修改内容的情况:

    handleUndo = () => {
      const quill = this.reactQuillRef.getEditor();
      // 先让编辑器获得焦点
      quill.focus();
      quill.history.undo();
    };
    
    handleRedo = () => {
      const quill = this.reactQuillRef.getEditor();
      quill.focus();
      quill.history.redo();
    };
    

    这个方法最直接,基本上能解决大部分焦点不同步的问题。

  • 确保ReactQuill与Quill实例状态同步
    如果你的组件没有绑定valueonChange,很可能会出现React状态和Quill实例状态脱节的情况。建议给ReactQuill加上状态绑定:

    class MyEditor extends React.Component {
      constructor(props) {
        super(props);
        this.state = { content: '' };
      }
    
      handleChange = (content) => {
        this.setState({ content });
      };
    
      render() {
        return (
          <ReactQuill
            ref={ref => this.reactQuillRef = ref}
            value={this.state.content}
            onChange={this.handleChange}
          />
        );
      }
    }
    

    这样ReactQuill的内部状态会和Quill实例保持一致,能减少很多因状态不同步导致的奇怪问题。

  • 提前缓存Quill实例
    可以在componentDidMount里把Quill实例缓存下来,避免每次调用时重复获取,也能减少ref引用的潜在问题:

    componentDidMount() {
      this.quillInstance = this.reactQuillRef.getEditor();
    }
    
    handleUndo = () => {
      if (!this.quillInstance) return;
      this.quillInstance.focus();
      this.quillInstance.history.undo();
    };
    

试一下这些方法,应该就能解决你遇到的焦点不同步问题了!

内容的提问来源于stack exchange,提问作者Dusan Jovanov

火山引擎 最新活动