# @cosmicmedia/react-native-markdown-display 中文文档

规范地址：https://npmcn.com/package/%40cosmicmedia/react-native-markdown-display/

版本：1\.1\.7
npm 元数据更新时间：2024-08-15T20:41:58.596Z
中文译文更新时间：2026-11-10T20:15:39.120Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40cosmicmedia/react-native-markdown-display
原文对照：https://npmcn.com/package/%40cosmicmedia/react-native-markdown-display/?lang=original
项目主页：https://github.com/cosmicmedia/react-native-markdown-display/
源码仓库：https://github.com/cosmicmedia/react-native-markdown-display

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：80.7 kB，29 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：4 个
- peer 依赖：react ^16\.2\.0 \|\| ^18\.0\.0，react-native \>=0\.50\.4
- 首次发布：2023-07-01T21:05:07.046Z
- 最新版本发布：2023-08-08T17:55:28.282Z
- 近 30 天下载量：6336（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：8（近 12 个月 0 个）

## 中文简介

用于反应-内生的马克下调渲染器,由CommonMark spec支持 + 添加语法扩展和糖分(URL自链接,打字机),最初由Mient-jan Stelling创建为反应-内生-马克下调-还原器

## 安装

```sh
npm install @cosmicmedia/react-native-markdown-display
```

也可以使用：`pnpm add @cosmicmedia/react-native-markdown-display`、`yarn add @cosmicmedia/react-native-markdown-display`、`bun add @cosmicmedia/react-native-markdown-display`

## README

# 反演原创标记下显示 [![npm version](https://badge.fury.io/js/react-native-markdown-display.svg)](https://badge.fury.io/js/react-native-markdown-display) [![Known Vulnerabilities](https://snyk.io/test/github/iamacup/react-native-markdown-display/badge.svg)](https://snyk.io/test/github/iamacup/react-native-markdown-display)

**这是叉子 [jonasmerlin/ react-native-markdown-display (原始内容存档于2018-09-31) (英语)](https://github.com/jonasmerlin/react-native-markdown-display) 它本身就是一个叉子 [错失/反应-内在- 标记- 显示](https://github.com/iamacup/react-native-markdown-display)。这个用于我们自己的React Industrial应用程序,用于渲染丰富的文本。 对你也有用!**

它是一个100%相容的CommonMark渲染器,一个反应-内在的标记下渲染器完成正确. 这是 **没有** 网络视图标记下渲染器,但渲染器使用其所有元素的本地组件。 这些组件可以根据需要被覆盖并样式.

### 与反应- 内置- 标记- 递归器相兼容

这是用来取代反应-内存-标记-降级-降级器,并有各种bug修正和增强- **由于新风格的规则如何运作, 可能需要一些调整**, (中文(简体) ), [查看下面的样式](https://npmcn.com/package/%40cosmicmedia/react-native-markdown-display/#readme-How-to-style-stuff)

### 安装

#### 雅伦

```npm
yarn add @cosmicmedia/react-native-markdown-display
```

#### 国家预防机制

```npm
npm install -S @cosmicmedia/react-native-markdown-display
```

### 开始

```jsx
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar} from 'react-native';

import Markdown from 'react-native-markdown-display';

const copy = `# h1 Heading 8-)

**This is some bold text!**

This is normal text
`;

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}>
          <Markdown>{copy}</Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;
```

### 道具和函数

这个 `<Markdown>` 对象取下列常用道具:

| 财产 | 默认 | 需求 | 说明 |
| --- | --- | --- | --- |
| `children` | 不详 | `true` | 缩放字符串来渲染,或者 [预处理的树](https://npmcn.com/package/%40cosmicmedia/react-native-markdown-display/#readme-pre-processing) |
| `style` | [来源](https://github.com/iamacup/react-native-markdown-display/blob/master/src/lib/styles.js) | `false` | 一个反对推翻各种规则的样式, [参见下面样式一节](https://npmcn.com/package/%40cosmicmedia/react-native-markdown-display/#readme-rules-and-styles) 需要更多信息 |
| `mergeStyle` | `true` | `false` | 如果真实, 当提供样式时, 单个项目与默认样式合并, 而不是覆盖 |
| `rules` | [来源](https://github.com/iamacup/react-native-markdown-display/blob/master/src/lib/renderRules.js) | `false` | 规定如何制作每个减记项的规则对象, [见下文规则一节](https://npmcn.com/package/%40cosmicmedia/react-native-markdown-display/#readme-rules) 需要更多信息 |
| `onLinkPress` | `import { Linking } from 'react-native';` 财务报告和审定财务报表 `Linking.openURL(url);` | `false` | 用于改变点击行为的处理器功能, [参见下面的处理链接部分](https://npmcn.com/package/%40cosmicmedia/react-native-markdown-display/#readme-handling-links) 需要更多信息 |
| `debugPrintTree` | `false` | `false` | 将打印出 AST 树到控制台, 帮助您看下调被翻译到什么 |

和一些额外的,较少使用的选项:

| 财产 | 默认 | 需求 | 说明 |
| --- | --- | --- | --- |
| `renderer` | `instanceOf(AstRenderer)` | `false` | 用于指定自定义渲染器,不能使用自定义渲染器的规则或样式道具. |
| `markdownit` | `instanceOf(MarkdownIt)` | `false` | 带有您的配置的自定义缩写实例, 默认为 `MarkdownIt({typographer: true})` |
| `maxTopLevelChildren` | `null` | `false` | 如果定义为数字,则仅先显示 `n` 许多顶级的孩子,然后会尝试出 `topLevelMaxExceededItem` |
| `topLevelMaxExceededItem` | `<Text key="dotdotdot">...</Text>` | `false` | 何时 `maxTopLevelChildren` 被击中。 一定要给它一把钥匙! |
| `allowedImageHandlers` | `['data:image/png;base64', 'data:image/gif;base64', 'data:image/jpeg;base64', 'https://', 'http://']` | `false` | 任何不从其中之一开始的图像都会有 `defaultImageHandler` 为它准备的值(除非 `defaultImageHandler` 在这样的情况下,它不会试图做任何事情) |
| `defaultImageHandler` | `http://` | `false` | 将准备到图像 URL,如果它不开始于 `allowedImageHandlers` 数组,如果设定为无效,它不会试图恢复,而只是不会产生任何东西. |

# 语法支持

标题

```
  # h1 Heading 8-)
  ## h2 Heading
  ### h3 Heading
  #### h4 Heading
  ##### h5 Heading
  ###### h6 Heading
```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-1.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-1.png) |

水平规则

```
  Some text above
  ___

  Some text in the middle

  ---

  Some text below
```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-2.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-2.png) |

强调

```
  **This is bold text**

  __This is bold text__

  *This is italic text*

  _This is italic text_

  ~~Strikethrough~~
```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-4.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-4.png) |

块名

```
  > Blockquotes can also be nested...
  >> ...by using additional greater-than signs right next to each other...
  > > > ...or with spaces between arrows.
```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-5.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-5.png) |

名单

```
  Unordered

  + Create a list by starting a line with `+`, `-`, or `*`
  + Sub-lists are made by indenting 2 spaces:
    - Marker character change forces new list start:
      * Ac tristique libero volutpat at
      + Facilisis in pretium nisl aliquet. This is a very long list item that will surely wrap onto the next line.
      - Nulla volutpat aliquam velit
  + Very easy!

  Ordered

  1. Lorem ipsum dolor sit amet
  2. Consectetur adipiscing elit. This is a very long list item that will surely wrap onto the next line.
  3. Integer molestie lorem at massa

  Start numbering with offset:

  57. foo
  58. bar
```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-6.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-6.png) |

代码

```
  Inline \`code\`

Indented code

      // Some comments
      line 1 of code
      line 2 of code
      line 3 of code

Block code "fences"

\`\`\`
Sample text here...
\`\`\`

Syntax highlighting

\`\`\` js
var foo = function (bar) {
return bar++;
};

console.log(foo(5));
\`\`\`

```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-7.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-7.png) |

表格

```

| Option | Description                                                               |
| ------ | ------------------------------------------------------------------------- |
| data   | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default.    |
| ext    | extension to be used for dest files.                                      |

Right aligned columns

| Option |                                                               Description |
| -----: | ------------------------------------------------------------------------: |
|   data | path to data files to supply the data that will be passed into templates. |
| engine |    engine to be used for processing templates. Handlebars is the default. |
|    ext |                                      extension to be used for dest files. |

```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-8.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-8.png) |

链接

```

[link text](https://www.google.com)

[link with title](https://www.google.com 'title text!')

Autoconverted link https://www.google.com (enable linkify to see)

```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-9.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-9.png) |

图像

```

![Minion](https://octodex.github.com/images/minion.png)
![Stormtroopocat](https://octodex.github.com/images/stormtroopocat.jpg 'The Stormtroopocat')

Like links, Images also have a footnote style syntax

![Alt text][id]

With a reference later in the document defining the URL location:

[id]: https://octodex.github.com/images/dojocat.jpg 'The Dojocat'

```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-10.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-10.png) |

类型替换

```

Enable typographer option to see result.

(c) (C) (r) (R) (tm) (TM) (p) (P) +-

test.. test... test..... test?..... test!....

!!!!!! ???? ,, -- ---

"Smartypants, double quotes" and 'single quotes'

```

| iOS系统 | 机器人 |
| --- | --- |
| ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/ios-3.png) | ![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/android-3.png) |

插件和扩展

用于 **额外** 语法支持可以使用任何可兼容的标记下- 它的插件添加 - [参见插件](https://www.npmjs.com/browse/keyword/markdown-it-plugin) 从马克下调的文件。 一体化的例子如下:

#### 步骤1

确定新组件,并将插件与已提供组件相融合。 我们可以使用 `debugPrintTree` 以查看我们执行的规则:

```jsx
import React from 'react';
import { SafeAreaView, ScrollView, StatusBar } from 'react-native';

import Markdown, { MarkdownIt } from 'react-native-markdown-display';
import blockEmbedPlugin from 'markdown-it-block-embed';

const markdownItInstance =
    MarkdownIt({typographer: true})
      .use(blockEmbedPlugin, {
        containerClassName: "video-embed"
      });

const copy = `
# Some header

@[youtube](lJIrF4YjHfQ)
`;

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}
        >
            <Markdown
              debugPrintTree
              markdownit={markdownItInstance}
            >
              {copy}
            </Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;

```

在控制台中,我们将看到以下的成树:

```
body
-heading1
--textgroup
---text
-video
```

带有以下错误消息 :

```
Warning, unknown render rule encountered: video. 'unknown' render rule used (by default, returns null - nothing rendered)
```

#### 步骤2

我们需要创建 **发布规则** 财务报告和审定财务报表 **样式** 处理此新 **"视频"** 组件

```jsx
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar} from 'react-native';

import Markdown, {MarkdownIt} from 'react-native-markdown-display';
import blockEmbedPlugin from 'markdown-it-block-embed';

const markdownItInstance = MarkdownIt({typographer: true}).use(
  blockEmbedPlugin,
  {
    containerClassName: 'video-embed',
  },
);

const copy = `
# Some header

@[youtube](lJIrF4YjHfQ)
`;

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}>
          <Markdown
            debugPrintTree
            markdownit={markdownItInstance}
            style={{
              video: {
                color: 'red',
              },
            }}
            rules={{
              video: (node, children, parent, styles) => {
                // examine the node properties to see what video we need to render
                console.log(node); // expected output of this is in readme.md below this code snip

                return (
                  <Text key={node.key} style={styles.video}>
                    Return a video component instead of this text component!
                  </Text>
                );
              },
            }}>
            {copy}
          </Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;
```

制作有意义的东西所需的所有视频属性 都在节点上,像这样:

```
{type: "video", sourceType: "video", sourceInfo: {…}, sourceMeta: null, block: true, …}
  attributes: {}
  block: true
  children: []
  content: ""
  index: 1
  key: "rnmr_1720a98f540_video"
  markup: "@[youtube](lJIrF4YjHfQ)"
  sourceInfo:
    service: YouTubeService
      env: PluginEnvironment {md: MarkdownIt, options: {…}, services: {…}}
      name: "youtube"
      options:
        height: 390
        width: 640
      serviceName: "youtube"
      videoID: "lJIrF4YjHfQ"
      videoReference: "lJIrF4YjHfQ"
  sourceMeta: null
  sourceType: "video"
  tokenIndex: 5
  type: "video"
```

#### 其他调试

你可以做一些额外的调试 标记下的例子 吐出这样的:

```jsx
import Markdown, {MarkdownIt} from 'react-native-markdown-display';
import blockEmbedPlugin from 'markdown-it-block-embed';

const markdownItInstance = MarkdownIt({typographer: true}).use(
  blockEmbedPlugin,
  {
    containerClassName: 'video-embed',
  },
);

const copy = `
# Some header

@[youtube](lJIrF4YjHfQ)
`;

// this shows you the tree that is used by the react-native-markdown-display
const astTree = markdownItInstance.parse(copy, {});
console.log(astTree);

//this contains the html that would be generated - not used by react-native-markdown-display but useful for reference
const html = markdownItInstance.render(copy);
console.log(html);
```

上面的代码会输出类似的东西:

```
astTree:

(4) [Token, Token, Token, Token]

0: Token {type: "heading_open", tag: "h1", attrs: null, map: Array(2), nesting: 1, …}
1: Token {type: "inline", tag: "", attrs: null, map: Array(2), nesting: 0, …}
2: Token {type: "heading_close", tag: "h1", attrs: null, map: null, nesting: -1, …}
3: Token {type: "video", tag: "div", attrs: null, map: Array(2), nesting: 0, …}

length: 4
```

```
html:


<h1>Some header</h1>
<div class="video-embed block-embed-service-youtube"><iframe type="text/html" src="//www.youtube.com/embed/lJIrF4YjHfQ" frameborder="0" width="640" height="390" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>
```
测试时全部标记下

测试所有情况下应用的样式都有效

```
Headings

  # h1 Heading 8-)
  ## h2 Heading
  ### h3 Heading
  #### h4 Heading
  ##### h5 Heading
  ###### h6 Heading


Horizontal Rules

  Some text above
  ___

  Some text in the middle

  ---

  Some text below


Emphasis

  **This is bold text**

  __This is bold text__

  *This is italic text*

  _This is italic text_

  ~~Strikethrough~~


Blockquotes

  > Blockquotes can also be nested...
  >> ...by using additional greater-than signs right next to each other...
  > > > ...or with spaces between arrows.


Lists

  Unordered

  + Create a list by starting a line with `+`, `-`, or `*`
  + Sub-lists are made by indenting 2 spaces:
    - Marker character change forces new list start:
      * Ac tristique libero volutpat at
      + Facilisis in pretium nisl aliquet. This is a very long list item that will surely wrap onto the next line.
      - Nulla volutpat aliquam velit
  + Very easy!

  Ordered

  1. Lorem ipsum dolor sit amet
  2. Consectetur adipiscing elit. This is a very long list item that will surely wrap onto the next line.
  3. Integer molestie lorem at massa

  Start numbering with offset:

  57. foo
  58. bar


Code

  Inline \`code\`

  Indented code

      // Some comments
      line 1 of code
      line 2 of code
      line 3 of code


  Block code "fences"

  \`\`\`
  Sample text here...
  \`\`\`

  Syntax highlighting

  \`\`\` js
  var foo = function (bar) {
    return bar++;
  };

  console.log(foo(5));
  \`\`\`


Tables

  | Option | Description |
  | ------ | ----------- |
  | data   | path to data files to supply the data that will be passed into templates. |
  | engine | engine to be used for processing templates. Handlebars is the default. |
  | ext    | extension to be used for dest files. |

  Right aligned columns

  | Option | Description |
  | ------:| -----------:|
  | data   | path to data files to supply the data that will be passed into templates. |
  | engine | engine to be used for processing templates. Handlebars is the default. |
  | ext    | extension to be used for dest files. |


Links

  [link text](https://www.google.com)

  [link with title](https://www.google.com "title text!")

  Autoconverted link https://www.google.com (enable linkify to see)


Images

  ![Minion](https://octodex.github.com/images/minion.png)
  ![Stormtroopocat](https://octodex.github.com/images/stormtroopocat.jpg "The Stormtroopocat")

  Like links, Images also have a footnote style syntax

  ![Alt text][id]

  With a reference later in the document defining the URL location:

  [id]: https://octodex.github.com/images/dojocat.jpg  "The Dojocat"


Typographic Replacements

  Enable typographer option to see result.

  (c) (C) (r) (R) (tm) (TM) (p) (P) +-

  test.. test... test..... test?..... test!....

  !!!!!! ???? ,,  -- ---

  "Smartypants, double quotes" and 'single quotes'

```

# 规则和样式

### 怎么样的风格的东西

文本样式的应用方式使得管理全局样式的改变更加方便,同时也允许对单个元素进行细微的调和.

想想CSS中的应用风格等执行. 更改 `body` 效果一切, 但可以在样式 / 组件树下进一步覆盖 .

**格式化“ text” 时要小心 :** 文本规则并不适用于所有文本,最显著的是列出点。 如果你想,例如,所有文本的颜色,请修改 `body` 样式.

示例

![](https://github.com/iamacup/react-native-markdown-display/raw/master/doc/images/style-example.png)

```jsx
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar} from 'react-native';

import Markdown from 'react-native-markdown-display';

const copy = `
This is some text which is red because of the body style, which is also really small!

\`\`\`
//This is a code block woooo

const cool = () => {
  console.log('????');
};
\`\`\`

and some more small text

# This is a h1
## this is a h2
### this is a h3
`;

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}>
          <Markdown
            style={{
              body: {color: 'red', fontSize: 10},
              heading1: {color: 'purple'},
              code_block: {color: 'black', fontSize: 14},
            }}>
            {copy}
          </Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;
```

### 样式

样式用来推翻某些规则的样式。 现有执行工作是: [这里](https://github.com/iamacup/react-native-markdown-display/blob/master/src/lib/styles.js)

**注:** 默认样式与现有执行合并,以更改此样式,参见 `mergeStyle` 道具

实例

```jsx
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar, StyleSheet} from 'react-native';

import Markdown from 'react-native-markdown-display';

const styles = StyleSheet.create({
  heading1: {
    fontSize: 32,
    backgroundColor: '#000000',
    color: '#FFFFFF',
  },
  heading2: {
    fontSize: 24,
  },
  heading3: {
    fontSize: 18,
  },
  heading4: {
    fontSize: 16,
  },
  heading5: {
    fontSize: 13,
  },
  heading6: {
    fontSize: 11,
  },
});

const copy = `
# h1 Heading 8-)
## h2 Heading 8-)
### h3 Heading 8-)

| Option | Description |
| ------ | ----------- |
| data   | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext    | extension to be used for dest files. |
`;

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}>
          <Markdown style={styles}>{copy}</Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;
```

### 规则

规则用于指定要如何显示某些元素。 现有执行工作是: [这里](https://github.com/iamacup/react-native-markdown-display/blob/master/src/lib/renderRules.js)

实例

```jsx
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar, Text} from 'react-native';

import Markdown from 'react-native-markdown-display';

const rules = {
  heading1: (node, children, parent, styles) => (
    <Text key={node.key} style={[styles.heading, styles.heading1]}>
      >> H1 TEXT HERE >> "{children}"
    </Text>
  ),
  heading2: (node, children, parent, styles) => (
    <Text key={node.key} style={[styles.heading, styles.heading2]}>
      >> H2 TEXT HERE >> "{children}"
    </Text>
  ),
  heading3: (node, children, parent, styles) => (
    <Text key={node.key} style={[styles.heading, styles.heading3]}>
      >> H3 TEXT HERE >> "{children}"
    </Text>
  ),
};

const copy = `
# h1 Heading 8-)
## h2 Heading 8-)
### h3 Heading 8-)

| Option | Description |
| ------ | ----------- |
| data   | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext    | extension to be used for dest files. |
`;

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}>
          <Markdown rules={rules}>{copy}</Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;
```

### 所有规则及其相关风格:

| 规则 | 样式 |
| --- | --- |
| `body` | `body` |
| `heading1` | `heading1` |
| `heading2` | `heading2` |
| `heading3` | `heading3` |
| `heading4` | `heading4` |
| `heading5` | `heading5` |
| `heading6` | `heading6` |
| `hr` | `hr` |
| `strong` | `strong` |
| `em` | `em` |
| `s` | `s` |
| `blockquote` | `blockquote` |
| `bullet_list` | `bullet_list` |
| `ordered_list` | `ordered_list` |
| `list_item` | `list_item` - 这是一个特殊的案例,它包含一组伪类 不符合渲染规则: `ordered_list_icon`, (中文(简体) ), `ordered_list_content`, (中文(简体) ), `bullet_list_icon`, (中文(简体) ), `bullet_list_content` |
| `code_inline` | `code_inline` |
| `code_block` | `code_block` |
| `fence` | `fence` |
| `table` | `table` |
| `thead` | `thead` |
| `tbody` | `tbody` |
| `th` | `th` |
| `tr` | `tr` |
| `td` | `td` |
| `link` | `link` |
| `blocklink` | `blocklink` |
| `image` | `image` |
| `text` | `text` |
| `textgroup` | `textgroup` |
| `paragraph` | `paragraph` |
| `hardbreak` | `hardbreak` |
| `softbreak` | `softbreak` |
| `pre` | `pre` |
| `inline` | `inline` |
| `span` | `span` |

# 处理链接

链接,默认情况下,将与 `import { Linking } from 'react-native';` 导入和 `Linking.openURL(url);` 电话.

可以通过两种方式之一推翻这种行为:

在 LinkPress 回电

```jsx
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar} from 'react-native';

import Markdown from 'react-native-markdown-display';

const copy = `[This is a link!](https://github.com/iamacup/react-native-markdown-display/)`;

const onLinkPress = (url) => {
  if (url) {
    // some custom logic
    return false;
  }

  // return true to open with `Linking.openURL
  // return false to handle it yourself
  return true;
};

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}>
          <Markdown onLinkPress={onLinkPress}>{copy}</Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;
```
使用自定义规则

您需要覆盖一个或两个 `link` 财务报告和审定财务报表 `blocklink`,原始的降级可以是 [在这里找到的](https://github.com/iamacup/react-native-markdown-display/blob/master/src/lib/renderRules.js)

像这样 `yourCustomHandlerFunctionOrLogicHere`数字 :

```jsx
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar, Text} from 'react-native';

import Markdown from 'react-native-markdown-display';

const copy = `[This is a link!](https://github.com/iamacup/react-native-markdown-display/)`;

const rules = {
  link: (node, children, parent, styles) => {
    return (
      <Text
        key={node.key}
        style={styles.link}
        onPress={() =>
          yourCustomHandlerFunctionOrLogicHere(node.attributes.href)
        }>
        {children}
      </Text>
    );
  },
};

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}>
          <Markdown rules={rules}>{copy}</Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;
```

# 禁用标记下的特定类型

您可以通过下面的减记属性来解析任何类型的减记,这在移动环境中非常有用. 请注意,为了方便起见,我们还出口 `MarkdownIt` 实例,所以您不必直接将它作为项目依赖性来删除某些类型的平分.

此示例将停止图像和链接 .

```jsx
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar, Text} from 'react-native';

import Markdown, {MarkdownIt} from 'react-native-markdown-display';

const copy = `
# This heading will show with formatting

[but this link will just](be displayed as this text)
`;

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}>
          <Markdown
            markdownit={MarkdownIt({typographer: true}).disable([
              'link',
              'image',
            ])}>
            {copy}
          </Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;
```

一份完整的可以关闭的东西列表 [这里](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.js)

### 预处理

可能需要在这个库外预先处理数据([相关讨论](https://github.com/iamacup/react-native-markdown-display/issues/79)) (中文(简体) ). 因此,可以直接通过一棵AST树,像这样的孩子:

```jsx
import React from 'react';
import {SafeAreaView, ScrollView, StatusBar, Text} from 'react-native';

import Markdown, {
  MarkdownIt,
  tokensToAST,
  stringToTokens,
} from 'react-native-markdown-display';

const markdownItInstance = MarkdownIt({typographer: true});

const copy = `
# Hello this is a title

This is some text with **BOLD!**
`;

const ast = tokensToAST(stringToTokens(copy, markdownItInstance));

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={{height: '100%'}}>
          <Markdown>{ast}</Markdown>
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

export default App;
```

### 其他说明

这是叉子 [反应- 内向- 标记- 投降器](https://github.com/mientjan/react-native-markdown-renderer)图书馆已经很久没有更新了 所以我从图书馆拿走了所有未解决的拉动请求 并进行了测试.

## 常见问题

### @cosmicmedia/react-native-markdown-display 是什么？

用于反应-内生的马克下调渲染器,由CommonMark spec支持 \+ 添加语法扩展和糖分\(URL自链接,打字机\),最初由Mient-jan Stelling创建为反应-内生-马克下调-还原器

### 如何安装 @cosmicmedia/react-native-markdown-display？

在项目目录运行 npm install @cosmicmedia/react-native-markdown-display，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^16\.2\.0 \|\| ^18\.0\.0）、react-native（\>=0\.50\.4）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @cosmicmedia/react-native-markdown-display 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @cosmicmedia/react-native-markdown-display 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @cosmicmedia/react-native-markdown-display 可以商用吗？

@cosmicmedia/react-native-markdown-display 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @cosmicmedia/react-native-markdown-display 的下载量有多少？

根据 npm 官方下载统计，@cosmicmedia/react-native-markdown-display 在 2026/10/11 – 2026/11/09 这 30 天内被下载 6,336 次，日均约 211 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @cosmicmedia/react-native-markdown-display 还在维护吗？

最新版本 1\.1\.7 发布于 2023/08/09（3 年前）；至今共发布 8 个版本，其中过去 12 个月发布了 0 个；首次发布于 2023/07/02。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

