react 中 wangeditor富文本编辑器中 insertFn函数
时间: 2024-03-12 13:43:04 浏览: 99
在 React 中使用 wangEditor 富文本编辑器时,insertFn 函数用于向编辑器中插入自定义内容。它的基本用法如下:
1. 首先需要在组件中创建一个 ref 对象,用于获取 wangEditor 实例:
```javascript
import React, { Component } from 'react';
import wangEditor from 'wangeditor';
class Editor extends Component {
constructor(props) {
super(props);
this.editorRef = React.createRef();
}
componentDidMount() {
const editor = new wangEditor(this.editorRef.current);
editor.create();
this.editor = editor;
}
render() {
return (
<div ref={this.editorRef} />
);
}
}
```
2. 在组件中定义 insertFn 函数:
```javascript
const insertFn = (content) => {
const editor = this.editor;
const range = editor.selection.getRange();
range.deleteContents();
const node = document.createElement('div');
node.innerHTML = content;
range.insertNode(node);
editor.selection.restoreSelection();
};
```
3. 在组件渲染时,将 insertFn 函数传递给 wangEditor 实例:
```javascript
componentDidMount() {
const editor = new wangEditor(this.editorRef.current);
editor.customConfig.onchange = (html) => {
this.props.onChange(html);
};
editor.customConfig.menus = [...];
editor.customConfig.insertFn = insertFn;
editor.create();
this.editor = editor;
}
```
这样就可以在编辑器中使用 insertFn 函数插入自定义内容了。
阅读全文
相关推荐
















