在React富文本编辑react-draft-wysiwyg中插入图片,在之后输入中文就会报错。
错误如下;
这个错误在Github有题issue但是没有被解决,我在简书上面找到了一遍文章,可以解决。
react富文本编辑器点击进去就可以看原文。
我参照原文,解决了问题,这是我的代码
import React, { Component } from 'react';
interface Props {
contentState: any;
block: any;
blockProps: any;
}
interface Sate {}
export const myBlockRenderer = (contentBlock: any): any => {
const type = contentBlock.getType();
// 图片类型转换为mediaComponent
if (type === 'atomic') {
return {
component: Media,
editable: false,
props: {
foo: 'bar',
},
};
}
};
class Media extends Component<Props, Sate> {
render() {
const { block, contentState } = this.props;
const data = contentState.getEntity(block.getEntityAt(0)).getData();
const emptyHtml = ' ';
return (
<div>
{emptyHtml}
<img
src={data.src}
alt={data.alt || ''}
style={{ height: data.height || 'auto', width: data.width || 'auto' }}
/>
</div>
);
}
}
然后在Editor组件里面使用customBlockRenderFunc即可,如下:
<Editor
editorState={editorState}
editorStyle={{ border: '1px solid black', minHeight: 200 }}
onEditorStateChange={this.onEditorStateChange}
customBlockRenderFunc={myBlockRenderer}
toolbar={{
inline: { inDropdown: true },
list: { inDropdown: true },
textAlign: { inDropdown: true },
link: { inDropdown: true },
history: { inDropdown: true },
image: { uploadCallback: this.uploadImageCallBack, alt: { present: true, mandatory: true } },
}}
/>
其实原文作者就是把富文本里面的图片重新包装了一下返回了。在另一篇文章里面也有说,但是没给解决方案。
draft.js 顶部插入一张图片,将光标定位到上一行,按delete键,报错
大家可以点击上面这个链接进去看看