我试图在光标位置插入以下块:
插入文本
我使用了以下方法来获得准确的光标位置:
我的函数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;
我也用ofwindow.getSelection().getRangeAt(0).startOffset代替this.jodit.selectionstart尝试了上面的代码,但问题仍然存在。
根据我的分析,onChange处理程序每次输入什么东西时都会更新游标位置,但是当我们更改游标位置时就不会再次更新它。
发布于 2021-04-04 10:27:40
在config对象中添加以下内容
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之后获得编辑器的实例。这应该能解决你的问题。
https://stackoverflow.com/questions/66921304
复制相似问题