求Draft-js保存编辑器状态并展示为HTML的教程/指南
Hey Greg, I totally get where you're coming from—dealing with Draft.js's raw state to HTML conversion can feel unnecessarily clunky when all you want is to render content for users without firing up the editor again. Let's break down some straightforward, simplified solutions for you:
1. Using Draft.js's Built-in Utilities (Streamlined)
Draft.js actually has a built-in convertToHTML function that you might have overlooked—you don't need to overcomplicate things with only convertToRaw/convertFromRaw. Here's a trimmed-down workflow:
Step 1: Save the Raw Editor State
When saving, you'll still use convertToRaw to get a serializable raw state (this is standard for persistence):
import { convertToRaw } from 'draft-js'; // When saving your editor's content const rawState = convertToRaw(editorState.getCurrentContent()); // Save rawState to your database/local storage as usual
Step 2: Convert Raw State to HTML
When you need to render the content for users, use convertFromRaw to restore the ContentState, then pass it to convertToHTML:
import { convertFromRaw, convertToHTML } from 'draft-js'; // Retrieve the saved raw state from your storage const savedRawState = /* your stored raw state data */; const contentState = convertFromRaw(savedRawState); const htmlContent = convertToHTML(contentState);
Step 3: Render the HTML Safely
In React, you can render the HTML with dangerouslySetInnerHTML, but always sanitize it first to prevent XSS attacks:
import DOMPurify from 'dompurify'; // Install via npm install dompurify // Sanitize the generated HTML const sanitizedHtml = DOMPurify.sanitize(htmlContent); // Render in your component return <div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} />;
2. Use a Third-Party Library for Even Less Boilerplate
If you want to cut down on repetitive code, libraries like draft-js-export-html simplify the conversion even further:
Step 1: Install the Library
npm install draft-js-export-html
Step 2: Convert Raw State to HTML Directly
This library lets you skip the convertFromRaw step entirely, converting raw state straight to HTML:
import { stateToHTML } from 'draft-js-export-html'; import { convertToRaw } from 'draft-js'; // When saving (same as before) const rawState = convertToRaw(editorState.getCurrentContent()); // When rendering const htmlContent = stateToHTML(rawState); // Sanitize and render using the same method as above
Key Tips to Avoid Headaches
- XSS Protection: Never skip sanitizing the HTML—
dompurifyis lightweight and essential for user-facing content. - Custom Styles: If you use custom blocks or inline styles, both
convertToHTMLandstateToHTMLaccept configuration options to map your custom styles to HTML elements/classes. - Why Save Raw State?: Saving raw state instead of HTML keeps your options open—you can still load the content back into the Draft.js editor later, while also being able to render it as HTML.
内容的提问来源于stack exchange,提问作者Greg Miller

