我正在创建一个组件,该组件将使用 Draft-js 显示来自后端的数据。来自后端的数据也使用 Draft-js 存储。数据未显示,也没有错误消息。
来自后端的示例数据在传递给 viewContent.js 之前被解析
你好世界
我试图创建一个变量来检查代码是否正常工作。我尝试了这种方法 const sample = <p>Hello World
。如果在 contenBlocks 上传递这个,这个就可以工作了。
视图内容.js
import {
EditorState,
ContentState,
convertFromHTML,
} from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
const viewContent = ({ content }) => {
const [editorState, setEditorState] = useState();
const clearState = () => {
ContentState.createFromText('');
};
const handleEditorChange = (state) => {
setEditorState(state);
let currentContentAsHTML = JSON.stringify(
draftToHtml(convertToRaw(editorState.getCurrentContent()))
);
convertedContent(currentContentAsHTML);
};
useEffect(() => {
const contentBlocks = convertFromHTML(content);
const contentState = ContentState.createFromBlockArray(
contentBlocks.contentBlocks,
contentBlocks.entityMap
);
setEditorState(EditorState.createWithContent(contentState));
}, [content]);
return (
<div className='comment-container p-2 border rounded-md'>
<Editor
editorState={editorState}
onEditorStateChange={handleEditorChange}
wrapperClassName='wrapper-class'
editorClassName='editor-class'
toolbarClassName='toolbar-class'
onClick={clearState}
/>
</div>
);
};
export default viewContent;
父组件
<viewContent
content={taskInfo.taskNote}
convertedContent={(convertedContent) =>
setTaskInfo((prevState) => ({
...prevState,
taskNote: convertedContent,
}))
}
/>