React項目中使用Markdown編輯器

一、需求說明

  • 項目中業(yè)務(wù)需要輸入數(shù)學(xué)公式,原先的富文本框編輯器解析不了,經(jīng)過跟組長討論后決定采用Markdown類型的編輯器,以便解析和展示數(shù)學(xué)公式。查閱資料及實踐后,最終形成以下方案,記錄下來以供參閱。
  • 組建依賴:編輯器使用 for-editor,內(nèi)容預(yù)覽及展示采用 react-markdown。數(shù)學(xué)公式支持及語法解析使用 remark-math、rehype-katex,數(shù)學(xué)公式的樣式展示需要 katex.min.css 文件支持,見下文。因為仍需解析之前輸入的富文本內(nèi)容,所以引入 rehype-raw 解析HTML文本。

二、組件樣式及目錄

  • 組件最終樣式:


    組件樣式.jpg
  • 目錄結(jié)構(gòu):


    目錄結(jié)構(gòu).jpg

三、相關(guān)代碼及說明

  • index.js:編輯器的主體代碼,具體的屬性請查閱相關(guān)文檔。
    • 預(yù)覽按鈕需手動添加,以 position 定位在編輯器上。
import React, { Fragment, useRef, useState } from 'react';
import { Button, Modal } from 'antd';
import ForEditor from 'for-editor';
import MdPreview from './md-preview';
import './index.less';

/** https://github.com/kkfor/for-editor
 * @param {string} value Markdown文本內(nèi)容
 * @param {() => void} onChange 更改內(nèi)容方法
 * @param {boolean} readOnly 只讀狀態(tài)
 */
function MdEditor({ value, onChange, readOnly = false }) {
  const [visible, setVisible] = useState(false); // 預(yù)覽彈框狀態(tài)
  const mdRef = useRef(null); // 編輯器ref

  // 工具欄菜單
  const toolbar = {
    h1: true, // h1
    h2: true, // h2
    h3: true, // h3
    h4: true, // h4
    img: true, // 圖片
    link: true, // 鏈接
    code: true, // 代碼塊
    // preview: true, // 預(yù)覽
    expand: true, // 全屏
    /* v0.0.9 */
    undo: true, // 撤銷
    redo: true, // 重做
    save: true, // 保存
    /* v0.2.3 */
    // subfield: true, // 單雙欄模式
  };

  // 上傳圖片
  // const addImg = (_file) => {
  //   mdRef.current.$img2Url(_file.name, 'file_url');
  // };

  return (
    <div className="label__md-editor">
      {readOnly ? <MdPreview content={value} /> : (
        <Fragment>
          <Button
            size="small"
            className="preview__md-button"
            onClick={() => setVisible(true)}
          >
            預(yù)覽
          </Button>
          <Modal
            title="Markdown內(nèi)容預(yù)覽"
            width="60%"
            okText="關(guān)閉"
            visible={visible}
            onOk={() => setVisible(false)}
            onCancel={() => setVisible(false)}
            cancelButtonProps={{ style: { display: 'none' } }}
          >
            <MdPreview content={value} />
          </Modal>

          <ForEditor
            placeholder="請輸入Markdown文本"
            height={160}
            ref={mdRef}
            lineNum={false}
            toolbar={toolbar}
            value={value}
            onChange={onChange}
            // addImg={_file => addImg(_file)}
          />
        </Fragment>
      )}
    </div>
  );
}

export default React.memo(MdEditor);
  • index.less:涉及樣式
.label__md-editor {
  position: relative;

  .preview__md-button {
    position: absolute;
    right: 44px;
    top: 11px;
  }

  .for-container textarea {
    height: 114%;
  }
}
  • md-preview.js:預(yù)覽組件
import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
import rehypeRaw from 'rehype-raw';

/** https://blog.csdn.net/weixin_44589651/article/details/121044772
 * @param {string} content Markdown文本內(nèi)容
 */
export default React.memo(({ content }) => (
  <ReactMarkdown
    remarkPlugins={[remarkMath]}
    rehypePlugins={[rehypeKatex, rehypeRaw]}
  >
    {content}
  </ReactMarkdown>
));
  • 在項目的 index.ejs 或 inde.html 文件中引入公式解析樣式文件,否則公式會亂掉
 <!-- 解析Markdown數(shù)學(xué)公式樣式 -->
  <link rel="stylesheet"  integrity="sha384-RZU/ijkSsFbcmivfdRBQDtwuwVqK7GMOw6IMvKyeWL2K5UAlyp6WonmB8m7Jd0Hn" crossorigin="anonymous">
  • package.json:組件涉及的依賴及版本
{
  "dependencies": {
    "antd": "3.26.16",
    "dva": "^2.6.0-beta.20",
    "for-editor": "^0.3.5", // Markdown編輯
    "react": "16.9.0",
    "react-dom": "16.9.0",
    "react-markdown": "7.1.0", // Markdown預(yù)覽
    "rehype-katex": "^6.0.2", // 數(shù)學(xué)公式katex語法
    "rehype-raw": "^6.1.1", // 支持HTML語法解析
    "remark-math": "^5.1.1" // 支持數(shù)學(xué)公式
  },
}

參考資料

附文

  • 1. 預(yù)覽時遇到的報錯

    • DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('percent<=0') is not a valid name.
    • 數(shù)據(jù):<p>TOP1% 0.1<percent<=0.25</p>
    • 原因:解析器把 <percent<=0 識別成了標(biāo)簽名
    • 解決:輸入數(shù)據(jù)時,< >英文字母 之間加空格
    • 例如:<p>TOP1% 0.1 < percent <= 0.25</p>
  • 2. Markdown語法數(shù)學(xué)公式

    • $a^2$a^2
    • $$\frac{\partial f}{\partial x} = 2\,\sqrt{a}\,x$$
      \frac{\partial f}{\partial x} = 2\,\sqrt{a}\,x
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容