首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我试图将一些HTML插入到我的光标位置上的jodit-react编辑器中,它以某种方式插入,但不完全是在我的光标位置。

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

Stack Overflow用户
提问于 2021-04-02 15:05:39
回答 1查看 2.3K关注 0票数 1

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

插入文本

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

  • this.jodit.selectionStart
  • window.getSelection().getRangeAt(0).startOffset

我的函数buttonClick将它插入到行中,但当我尝试插入它时,它无法恢复已更改的光标位置。

代码语言:javascript
运行
复制
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;

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

根据我的分析,onChange处理程序每次输入什么东西时都会更新游标位置,但是当我们更改游标位置时就不会再次更新它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-04 10:27:40

在config对象中添加以下内容

代码语言:javascript
运行
复制
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之后获得编辑器的实例。这应该能解决你的问题。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66921304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档