我正在尝试为我的博客开发一个新功能,即用于撰写文章的 Markdown 编辑器。
我选择@tailwindcss/typography
了markdown-it来做到这一点,所以这是我的全部依赖项:
包.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"
}
}
下面的代码是这个功能的组件,包括一个编辑区和一个预览区。但是,它没有用。
当我运行此代码时,它会像这样呈现出来,而无需排版<h1>
标签。
但是,如果我替换md.render(markdown)
(<h1>hello</h1>
markdown-it 的渲染结果),它似乎“工作”,看起来像这样。
编辑器.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;
为什么会发生这些事情?以及如何使其符合预期?