React富文本编辑器开发
import React, { useState } from 'react';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
const RichTextEditor = ({ content, onChange }) => {
const [editorState, setEditorState] = useState(EditorState.createEmpty());
// 当组件的props.content更新时,更新editorState
React.useEffect(() => {
if (content) {
const blocksFromHtml = htmlToDraft(content);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
setEditorState(EditorState.createWithContent(contentState));
}
}, [content]);
// 将editorState转换为HTML并在状态更改时通知父组件
const handleEditorChange = (editorState) => {
setEditorState(editorState);
onChange(draftToHtml(convertToRaw(editorState.getCurrentContent())));
};
return (
<Editor
editorState={editorState}
onEditorStateChange={handleEditorChange}
// 其他需要的属性和配置...
/>
);
};
export default RichTextEditor;
这个代码示例展示了如何创建一个React富文本编辑器组件,该组件接受HTML内容作为props,并在内部状态更新时通知父组件当前的HTML内容。这个示例使用了react-draft-wysiwyg
库和相关的Draft.js库来实现编辑功能。
评论已关闭