123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- import React from 'react';
- import E from 'wangeditor';
- import { fetch, apis } from '../../utils/request';
-
- /**
- * @param {*} props
- * @returns
- */
- class Wangedit extends React.Component {
- constructor(props, context) {
- super(props, context);
- this.state = {
- html: undefined,
- contenteditable: props.contenteditable == false ? false : true
- }
- this.editor = undefined;
- }
-
- render() {
- return (
- <div ref="editorElem" style={{ textAlign: 'left' }}>
- </div>
- );
- }
-
- componentDidMount() {
- const elem = this.refs.editorElem
- this.editor = new E(elem)
- // 使用 onchange 函数监听内容的变化
- this.editor.customConfig.onchange = html => {
- this.setState({ html })
-
- if (typeof this.props.onChange === 'function') {
- this.props.onChange(html)
- }
- }
- this.editor.customConfig.zIndex = 100
- this.editor.customConfig.uploadImgMaxLength = 1
- this.editor.customConfig.customUploadImg = function (files, insert) {
- if (!files.length) return
-
- const data = new FormData()
- data.append('file', files[0])
-
- fetch(apis.image.upload)({data}).then(insert)
- }
- this.editor.customConfig.menus = [
- 'head', // 标题
- 'bold', // 粗体
- 'fontSize', // 字号
- 'fontName', // 字体
- 'italic', // 斜体
- 'underline', // 下划线
- 'strikeThrough', // 删除线
- 'foreColor', // 文字颜色
- 'backColor', // 背景颜色
- 'list', // 列表
- 'justify', // 对齐方式
- 'quote', // 引用
- 'image', // 插入图片
- 'undo', // 撤销
- 'redo' // 重复
- ]
-
- // 过滤 word 字符
- this.editor.customConfig.pasteFilterStyle = false
- this.editor.customConfig.pasteTextHandle = function(content) {
- const regs = [
- /<!--\[if [\s\S]*?endif\]-->/ig,
- /<[a-zA-Z0-9]+\:[^>]+>[^>]*<\/[a-zA-Z0-9]+\:[^>]+>/ig,
- /<[a-zA-Z0-9]+\:[^>]+\/>/ig,
- /<style>[\s\S]*?<\/style>/ig,
- ]
-
- return regs.reduce((acc, reg) => {
- return acc.replace(reg, '')
- }, content)
- }
-
- this.editor.create()
- this.editor.$textElem.attr('contenteditable',this.state.contenteditable);
- this.editor.customConfig.uploadImgShowBase64 = true
- this.editor.txt.html(this.props.value)
- }
-
- componentDidUpdate(props, state) {
- if (this.props.value && !state.html) {
- if (this.editor) {
- this.editor.txt.html(this.props.value)
- }
- }
- }
-
- /**
- *增加这个 shouldComponentUpdate 生命函数
- 处理自动聚焦到富文本上
- *
- * @param {*} nextProps
- * @returns
- * @memberof Wangedit
- */
- shouldComponentUpdate(nextProps) {
- return nextProps.value !== this.editor.txt.html()
- }
- }
-
- export default Wangedit
|