安装
npm i react-quill
引入
import ReactQuill from 'react-quill';
import 'quill/dist/quill.snow.css';
state里面写配置 这是我的配置 也可以根据官方配置,这里的图片我用的是自定义上传再插入,特别注意:要改变this指向
this.state={
text:"",
modules: {
toolbar: {
container: [
[{ header: [1, 2,3, 4, 5, 6, false] }],
['bold', 'italic', 'underline', 'strike', ],
[{ list: 'ordered' }, { list: 'bullet' }],
[{ 'align': [] }],
[{ 'color': [] }, { 'background': [] }],
['link', 'image'],
['clean']
],
handlers: {
image() {
imageHandler.call(this, props.action);
},
}
},
},
}
this.handleChange = this.handleChange.bind(this)
图片上传 message是antd组件 这里我把函数定义到 class 上边了全局函数,如果不写自定义上传图片,他会自动转换成base64 ,
function imageHandler(action){
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = () => {
const file = input.files[0];
const fd = new FormData();
fd.append('file', file);
const hide = message.loading('上传中...', 0);
axios({
method: 'post',
url: '',
headers:{'Content-Type': 'multipart/form-data'},
data:fd
}).then((res) => {
const range = this.quill.getSelection();
this.quill.insertEmbed(range.index, 'image', res."接口返回的地址");
let index = range ? range.index : 0;
this.quill.setSelection(index + 1);//光标位置加1
hide();
})
}
}
获取富文本内容,这里的this指向富文本不指向class ,要在构造器里改变this指向
handleChange(value) {
console.log(value);
this.setState({
text:value
})
}
组件,一定要加上这个class名字,否则空格不回显(className=“ql-editor”)
<ReactQuill
theme="snow"
value={ this.state.text }
onChange={this.handleChange}
modules={modules}
className=" ql-editor"
/>
展示页面也要加上 这个 class名字
<div dangerouslySetInnerHTML={{__html: this.state.text}} className="ql-editor"></div>