记录一些常见的问题以及使用
1. 初始化赋值
import htmlToDraft from 'html-to-draftjs'
import { ContentState as DraftContentState } from 'draft-js'
import { EditorState,, convertToRaw } from 'draft-js'const { initialContent } = propsuseEffect(() => {if (initialContent) {try {const contentBlock = htmlToDraft(initialContent)if (contentBlock) {const contentState = DraftContentState.createFromBlockArray(contentBlock.contentBlocks)setEditorState(EditorState.createWithContent(contentState))// Convert ContentState to RawDraftContentStateconst rawContentState = convertToRaw(contentState)console.log('RawDraftContentState:', rawContentState)}} catch (error) {console.error('Error parsing HTML content:', error)}}}, [initialContent])
2.上传图片后,未直接插入富文本的问题解决
上传图片
// 定义处理上传图片的回调函数const handleImageUpload = async (file) => {try {// 将图片上传到服务器const formData = new FormData()formData.append('images', file)const response = await fetch('接口地址', {method: 'POST',body: formData})const data = await response.json()//读取图片的 URL return {data: {link:`接口地址?imagePath=` +data.data}}} catch (error) {console.error('Error uploading image:', error)throw error}}
未直接插入富文本编辑器的问题解决
Editor的toolbar需要添加previewImage: true,inputAccept: 'image/*'完整toolbartoolbar={{image: {urlEnabled: true,uploadEnabled: true,alignmentEnabled: true, // 是否显示排列按钮 相当于text-alignuploadCallback: handleImageUpload, // 设置上传图片的回调函数previewImage: true,inputAccept: 'image/*'},fontFamily: {options: ['宋体','黑体','楷体','微软雅黑','Arial','Georgia','Impact','Tahoma','Times New Roman','Verdana']}}}
3.富文本插入图片后无法输入中文的问题解决
Editor添加属性 customBlockRenderFunc={myBlockRenderer}import React, { Component } from 'react';export const myBlockRenderer = contentBlock => {const type = contentBlock.getType();// 图片类型转换为mediaComponentif (type === 'atomic') {return {component: Media,editable: false,props: {foo: 'bar',},};}
};class Media extends Component {constructor(props) {super(props)this.state = {}}render() {const { block, contentState } = this.props;console.log(this.props);const data = contentState.getEntity(block.getEntityAt(0)).getData();const emptyHtml = ' ';return (<div>{emptyHtml}<imgsrc={data.src}alt={data.alt || ''}/></div>);}
}