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

如何在React中通过dangerouslySetInnerHTML正确渲染Unicode字符?

在React中正确渲染API返回的含Unicode字符的HTML内容

1. 修复字符编码乱码

你看到的’、“这类乱码,是字符编码不匹配导致的(大多是API输出UTF-8编码内容,但前端解析时编码不一致)。可以用以下函数修复:

const fixEncoding = (str) => {
  return decodeURIComponent(escape(str));
};

将API返回的原始字符串传入该函数,就能把乱码转换为正确的Unicode字符(比如We’re会转为We’re,“misfits that fit”转为“misfits that fit”)。

2. 渲染HTML内容

React默认会转义HTML标签和实体,要正确渲染<p>和&nbsp;,需要使用dangerouslySetInnerHTML:

import React from 'react';

const fixEncoding = (str) => {
  return decodeURIComponent(escape(str));
};

const JobPost = () => {
  // API返回的原始内容
  const rawApiContent = `<p>We’re looking for a Customer Success Manager, Scale to join our team of five “misfits that fit”.&nbsp;</p>`;
  const processedContent = fixEncoding(rawApiContent);

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

export default JobPost;

关键注意点

  • dangerouslySetInnerHTML存在XSS风险,仅当API返回的内容完全可信(比如自有后端输出)时使用;如果是用户生成的内容,必须先做XSS过滤。
  • 最彻底的解决方式是让后端调整输出编码为标准UTF-8,从根源避免乱码问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:26:06