Tailwind/typography 如何在 React 项目中与 markdown-it 协同工作?

How can Tailwind/typography work well with markdown-it in a React project?

我正在尝试为我的博客开发一个新功能,即用于撰写文章的 Markdown 编辑器。

我选择 @tailwindcss/typography and markdown-it 这样做,所以这是我的全部依赖关系:

package.json

{
 "dependencies": {
    "firebase": "^9.0.0-beta.7",
    "markdown-it": "^12.2.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "@babel/preset-react": "^7.14.5",
    "@tailwindcss/typography": "^0.4.1",
    "autoprefixer": "^10.3.2",
    "babel-loader": "^8.2.2",
    "css-loader": "^6.2.0",
    "dotenv-webpack": "^7.0.3",
    "html-webpack-plugin": "^5.3.2",
    "postcss": "^8.3.6",
    "postcss-cli": "^8.3.1",
    "postcss-loader": "^6.1.1",
    "style-loader": "^3.2.1",
    "tailwindcss": "^2.2.7",
    "webpack": "^5.51.1",
    "webpack-cli": "^4.8.0",
    "webpack-dev-server": "^4.0.0"
  }
}

以下代码是该功能的组件,包括编辑区和预览区。但是,它没有用。

当我 运行 这段代码时,它呈现为 this,没有排版 <h1> 标签。

但是,如果我用 <h1>hello</h1>(markdown-it 的渲染结果)替换 md.render(markdown),它似乎“有效”,看起来像 this。

Editor.jsx
import React, { useState } from "react";
const md = require("markdown-it")('commonmark');


const Editor = () => {
  const [markdown, setMarkdown] = useState("# hello");
  const onTextChange = (e) => {
    setMarkdown(e.target.value);
  }

  return (
    <div>
      <form>
        <textarea onChange={(e) => onTextChange(e)}>
          {markdown}
        </textarea>
      </form>

      <div id="preview" className="prose">
        {md.render(markdown)} {/* <h1>hello</h1> */}
      </div>

    </div>
  )
}

export default Editor;

为什么会发生这些事情?我怎样才能达到预期 运行?

使用react-markdown代替markdown-it

这里有一个例子:

import ReactMarkdown from "react-markdown";

<div className="prose">
    <ReactMarkdown>{markdown}</ReactMarkdown>
</div>

它将在页面中将提供的内容呈现为 DOM,并且 Tailwind/typography 完美地设置这些元素的样式。