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

React Native中<Text>组件实现dangerouslySetInnerHTML等价效果的方法

在React Native的组件中渲染HTML内容的方案

React Native的<Text>组件本身不支持直接解析HTML,没法像Web端那样用dangerouslySetInnerHTML,但可以通过下面几种方式实现类似效果:

1. 使用第三方库(推荐)

最常用的是react-native-render-html,它能解析大部分HTML标签并转换成React Native可识别的组件。

步骤:

  • 先安装依赖:
npm install react-native-render-html
# 或者用yarn
yarn add react-native-render-html
  • 然后在组件中使用:
import React from 'react';
import { View } from 'react-native';
import RenderHTML from 'react-native-render-html';

const MyComponent = () => {
  const htmlContent = '<p>这是一段<b>加粗</b>的文本,还有<br>换行效果</p>';
  
  return (
    <View>
      <RenderHTML contentWidth={300} source={{ html: htmlContent }} />
    </View>
  );
};

export default MyComponent;

这个库支持自定义样式、处理图片和链接等,适配性很强。

2. 手动解析简单HTML(适合轻量场景)

如果你的HTML只有少量简单标签(比如<b>、<i>、<br>),可以手动拆分字符串并嵌套<Text>组件:

import React from 'react';
import { Text, View } from 'react-native';

const parseSimpleHtml = (html) => {
  // 处理换行标签
  const lines = html.split('<br>');
  return lines.map((line, index) => {
    // 处理加粗标签
    const parts = line.split(/(<b>|<\/b>)/);
    const styledParts = parts.map((part, partIndex) => {
      if (part === '<b>') return null;
      if (part === '</b>') return null;
      return part.includes('<b>') ? (
        <Text key={partIndex} style={{ fontWeight: 'bold' }}>
          {part.replace('<b>', '').replace('</b>', '')}
        </Text>
      ) : (
        <Text key={partIndex}>{part}</Text>
      );
    });
    return (
      <Text key={index}>
        {styledParts}
        {index !== lines.length - 1 && '\n'}
      </Text>
    );
  });
};

const MyComponent = () => {
  const htmlContent = '普通文本<b>加粗内容</b>,<br>换一行继续';
  
  return (
    <View>
      {parseSimpleHtml(htmlContent)}
    </View>
  );
};

export default MyComponent;

这种方式不用依赖第三方库,但只适合标签少的场景,复杂HTML会很麻烦。

3. 使用WebView(不推荐)

如果HTML结构特别复杂(比如包含CSS、JS),可以用WebView来渲染,但这种方式性能差,和原生组件交互也不方便,除非必要不建议用:

import React from 'react';
import { WebView } from 'react-native-webview';

const MyComponent = () => {
  const htmlContent = '<html><body><p>这是一段带<style>p{color:red;}</style>的HTML</p></body></html>';
  
  return (
    <WebView
      source={{ html: htmlContent }}
      style={{ height: 100, width: '100%' }}
    />
  );
};

export default MyComponent;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 11:57:08