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

React Native中如何将标记的特定文本转为粗体显示?

React Native 实现Markdown粗体文本渲染的解决方案

为什么直接替换HTML标签没用

React Native不支持直接渲染HTML字符串,你替换得到的<b>Lorem</b>只会被当作普通文本输出,必须用React Native的组件体系来处理。


方法1:手动拆分字符串,用Text组件实现粗体

利用React Native的Text组件可以嵌套的特性,拆分带**标记的字符串,将需要加粗的部分用带样式的Text包裹:

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

const parseBoldText = (rawText) => {
  const textSegments = rawText.split(/\*\*/);
  const renderedElements = [];

  textSegments.forEach((segment, idx) => {
    // 奇数位的片段是**包裹的加粗内容
    if (idx % 2 === 1) {
      renderedElements.push(
        <Text key={idx} style={{ fontWeight: 'bold' }}>
          {segment}
        </Text>
      );
    } else if (segment) {
      renderedElements.push(<Text key={idx}>{segment}</Text>);
    }
  });

  return renderedElements;
};

export default function BoldTextDemo() {
  const sourceText = '**Lorem** ipsum dolor sit, amet consectetur adipisicing elit.';

  return (
    <View style={{ padding: 20 }}>
      <Text>{parseBoldText(sourceText)}</Text>
    </View>
  );
}

方法2:用第三方库解析Markdown(适合复杂场景)

如果需要处理更多Markdown语法,推荐使用专门的解析库,比如react-native-markdown-display:

  1. 安装依赖:
npm install react-native-markdown-display --save
# 或 yarn
yarn add react-native-markdown-display
  1. 代码示例:
import React from 'react';
import { View } from 'react-native';
import Markdown from 'react-native-markdown-display';

export default function MarkdownDemo() {
  const sourceText = '**Lorem** ipsum dolor sit, amet consectetur adipisicing elit.';

  return (
    <View style={{ padding: 20 }}>
      <Markdown>{sourceText}</Markdown>
    </View>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:55:27