使用 `react-remark` 渲染 Markdown 教程

随笔3周前发布 读人度己
51 0 0

使用 react-remark 渲染 Markdown 教程

react-remarkReact component and hook to use remark to render markdown项目地址:https://gitcode.com/gh_mirrors/re/react-remark

项目介绍

react-remark 是一个用于将 Markdown 渲染为 React 组件的开源项目。它结合了 remarkrehype 生态系统,提供了强大的 Markdown 解析和渲染功能。该项目支持插件扩展,可以轻松实现自定义的 Markdown 渲染效果。

项目快速启动

安装

首先,你需要安装 react-remark 及其依赖:

npm install react-remark remark-gemoji rehype-slug rehype-autolink-headings

基本使用

以下是一个简单的示例,展示如何使用 react-remark 渲染 Markdown:

  1. import React from 'react';

  2. import { useRemark } from 'react-remark';

  3. const ExampleComponent = () => {

  4. const [reactContent, setMarkdownSource] = useRemark({

  5. remarkPlugins: [require('remark-gemoji')],

  6. rehypePlugins: [require('rehype-slug'), require('rehype-autolink-headings')],

  7. });

  8. React.useEffect(() => {

  9. setMarkdownSource('# markdown header');

  10. }, []);

  11. return reactContent;

  12. };

  13. export default ExampleComponent;

应用案例和最佳实践

动态更新 Markdown 内容

你可以通过输入框动态更新 Markdown 内容:

  1. import React from 'react';

  2. import { useRemark } from 'react-remark';

  3. const ExampleComponent = () => {

  4. const [reactContent, setMarkdownSource] = useRemark();

  5. return (

  6. <>

  7. <input

  8. type="text"

  9. onChange={(e) => setMarkdownSource(e.currentTarget.value)}

  10. />

  11. {reactContent}

  12. </>

  13. );

  14. };

  15. export default ExampleComponent;

服务器端渲染

react-remark 也支持服务器端渲染:

  1. import React from 'react';

  2. import { useRemarkSync } from 'react-remark';

  3. const ExampleComponent = () => {

  4. const reactContent = useRemarkSync('# markdown header');

  5. return reactContent;

  6. };

  7. export default ExampleComponent;

典型生态项目

remark-gemoji

remark-gemoji 是一个 remark 插件,用于将 Gemoji 短代码转换为对应的 Unicode 字符。

rehype-slug

rehype-slug 是一个 rehype 插件,用于为 Markdown 标题添加 id 属性,方便生成锚点链接。

rehype-autolink-headings

rehype-autolink-headings 是一个 rehype 插件,用于自动为 Markdown 标题添加链接。

通过这些插件的组合使用,你可以构建出功能丰富的 Markdown 渲染系统。

react-remarkReact component and hook to use remark to render markdown项目地址:https://gitcode.com/gh_mirrors/re/react-remark

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...