解决Unknown DraftEntity key null 插入图片,再输入会报错问题
最近在用react+draft.js编写富文本编辑器的时候遇到一个错误提示:Unknown DraftEntity key: null ,当时是写插入图片插入成功后在输入文字这一操作的时候出现的。
对比官方Demo上有一个易错的点(注意一下 其中的insertAtomicBlock函数的第三个参数不是一个空字符串,而是一个含有空格的字符串!!!!!!)
editorState: AtomicBlockUtils.insertAtomicBlock(
newEditorState,
entityKey,
' '
),
主要解决方案
自定义customBlockRenderFunc的方法
新建customBlockRenderFunc.tsx
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.tsx引入
// 该文件是为了兼容draftjs报错的问题********重要********不可删除********
import {myBlockRenderer} from './customBlockRenderFunc.tsx'
const Editor: React.FC<CreateFormProps> = (props) => {
return (
<Editor
editorClassName="demo-editor"
editorState={editorState}
onEditorStateChange={onEditorStateChange}
customBlockRenderFunc={myBlockRenderer}
localization={{
locale: 'zh',
}}
toolbar={
{
options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'embedded', 'emoji', 'image', 'remove', 'history'],
image: {
uploadCallback: uploadImageCallBack,
alt: { present: true, previewImage: true },
previewImage: true,
}
}
}
/>
)
}
export default Editor
其实就是把富文本里面的图片重新包装了一下返回了