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

如何在React Native中实现类似HTML的code与pre标签的代码展示功能

错误原因说明

你遇到的报错是因为React Native 不支持HTML原生标签,所有在JSX中使用的组件必须是React Native内置组件(首字母大写,如Text/View)或者自定义的首字母大写组件,<pre>/<code>是Web专属标签,RN运行时无法识别,才会抛出配置不存在的错误。

原生实现方案(无第三方依赖)

如果仅需要简单展示无高亮的代码,可以直接用Text组件配合样式实现,示例代码:

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

const CodeBlock = ({ code }) => {
  return (
    <View style={styles.codeContainer}>
      <Text style={styles.codeText}>{code}</Text>
    </View>
  )
}

const styles = StyleSheet.create({
  codeContainer: {
    backgroundColor: '#282c34',
    padding: 16,
    borderRadius: 8,
    marginVertical: 8,
  },
  codeText: {
    color: '#abb2bf',
    // 跨平台等宽字体配置
    fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace',
    fontSize: 14,
    lineHeight: 20,
  }
})

该方案的局限是没有语法高亮,需要自行处理关键字、注释等内容的样式区分,仅适合简单代码展示场景。

第三方库实现方案(带语法高亮)

以下是经过RN生态验证的适配库,可直接满足代码高亮需求:

  • react-native-syntax-highlighter:目前使用最广泛的RN代码高亮库,支持上百种编程语言,内置数十套主流代码主题(如Atom One Dark、Github Light等),支持自定义行号、换行、复制按钮等扩展功能,纯JS实现无需修改原生配置,兼容所有RN版本。
  • @ui-kitten/components/CodeHighlighter:如果你的项目已经接入了UI Kitten组件库,可以直接使用内置的CodeHighlighter组件,和库内其他组件样式统一,无需额外引入其他依赖。

react-native-syntax-highlighter使用示例:

import { SyntaxHighlighter } from 'react-native-syntax-highlighter';
// 引入高亮主题
import { atomOneDark } from 'react-syntax-highlighter/dist/esm/styles/hljs';

const CodeDemo = () => {
  const codeString = `const sum = (a, b) => {
  return a + b;
}`;
  return (
    <SyntaxHighlighter 
      language="javascript" 
      style={atomOneDark}
      fontSize={14}
      showLineNumbers={true}
    >
      {codeString}
    </SyntaxHighlighter>
  )
}

内容的提问来源于stack exchange,提问作者D. K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:06:02