我试图在我的光标位置将一些 HTML 插入到 jodit-react 编辑器中,它以某种方式插入但不完全在我的光标位置

I'm trying to insert some HTML into jodit-react editor on my cursor position, it somehow inserts but not exactly at my cursor position

我正在尝试在光标位置插入以下块:

插入文本

我使用了以下方法来获取准确的光标位置:

我的函数 buttonClick 将它插入行内,但是当我尝试插入它时无法重新捕获更改的光标位置。

import React from "react";
import ReactDOM from "react-dom";
import jodit from "jodit";
import "./App.css";
import JoditEditor from "jodit-react";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      content: "",
      pos: 0,
    };
  }

  updateContent = (value) => {
    this.setState({
      content: value,
      pos: window.getSelection().getRangeAt(0).startOffset,
    });
  };
  buttonClick = (event) => {
    var abc = this.state.content.slice(
      this.jodit.selectionStart,
      this.jodit.selectionEnd + 1
    );
    var startString = this.state.content.substring(0, this.state.pos + 3);
    var endString = this.state.content.substring(this.jodit.selectionEnd);
    console.log("abc" + startString + "::::::" + endString);
    this.setState({
      content: startString + '<a href="#">Inserted Text</a>' + endString,
    });
  };
  config = {
    readonly: false,
  };
  /**
   * @property Jodit jodit instance of native Jodit
   */
  jodit;
  setRef = (jodit) => (this.jodit = jodit);
  render() {
    return (
      <>
        <JoditEditor
          ref={this.setRef}
          value={this.state.content}
          config={this.config}
          tabIndex={1} // tabIndex of textarea
          onBlur={this.onFocusRemove}
          onChange={this.updateContent}
        />
        <button onClick={this.buttonClick}>insert</button>
      </>
    );
  }
}

export default App;

我也用 this.jodit.selectionstart 代替 window.getSelection().getRangeAt(0).startOffset 尝试了上面的代码,但问题仍然存在。

根据我的分析,onChange 处理程序会在我们输入内容时更新光标位置,但是当我们更改光标位置时它不会再次更新。

在配置对象中添加以下内容

config = {
      readonly: false, // all options from https://xdsoft.net/jodit/doc/
      events: 
           { 
            afterInit: (instance) => { this.jodit = instance; } 

}


buttonClick = (event) => { 
     this.jodit.selection.insertHTML('<a href="">Anchor Tag</a>'); 
};

这样您将在afterInit 之后获得编辑器的实例。 这应该可以解决您的问题。