You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:React无法将JSON中的HTML字符串转换为文本

Fixing React’s Unparsed HTML String Issue

Hey there! I totally get how frustrating it is when React doesn’t render your stored HTML strings the way you expect—let’s break down what’s happening and get this fixed right away.

Why Your HTML Isn’t Rendering Correctly

React automatically escapes all text content to protect against XSS attacks. That means if you try to render a variable like const myHtml = "<strong>Hi!</strong>" directly, React will show you the raw string <strong>Hi!</strong> instead of bold text.

The Right Way to Render HTML Strings in React

React provides an explicit prop called dangerouslySetInnerHTML for this exact scenario. Even though the name sounds scary, it’s safe to use as long as you trust the source of your HTML (e.g., it’s generated by your own code, not user-inputted content).

Here’s a working example:

function HtmlRenderer() {
  // Your stored HTML string
  const storedHtml = "<p>This is <em>formatted</em> text with a <a href='#'>link</a>!</p>";

  return (
    <div dangerouslySetInnerHTML={{ __html: storedHtml }} />
  );
}

This tells React to skip escaping and render the HTML directly as DOM elements.

Why DOMParser Was Throwing Errors

Chances are, you tried to use DOMParser and then inject the raw DOM node into your React component—React doesn’t accept native DOM nodes as children, which is why you saw an error. For example, this code would break:

// ❌ This will throw an error
function BrokenRenderer() {
  const htmlString = "<p>Test content</p>";
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlString, "text/html");
  const rawElement = doc.body.firstChild;

  return <div>{rawElement}</div>; // React can't render native DOM nodes directly
}

You could convert the parsed DOM to React elements with libraries like html-react-parser, but dangerouslySetInnerHTML is simpler for most cases.

Important Note for User-Provided Content

If your HTML comes from user input (like comments or form submissions), never use dangerouslySetInnerHTML directly—it’s a huge XSS risk. Instead, use a sanitization library like sanitize-html to clean the HTML first, then render it safely.

内容的提问来源于stack exchange,提问作者Saem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:56:39