如何解决我试图在我的光标位置将一些 HTML 插入到 jodit-react 编辑器中,它以某种方式插入但不完全在我的光标位置
我正在尝试在光标位置插入以下块:
插入的文本
- this.jodit.selectionStart
- window.getSelection().getRangeAt(0).startOffset
我的函数 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之后得到编辑器的实例。 这应该可以解决您的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。