问题描述
如何在 HTML 文本区域中使用 Markdown 属性,有点像堆栈溢出的正文区域?
当然,我的标准文本区域是这样制作的:
<textarea className="form__input form__group"
value={body}
onChange={e => setBody(e.target.value)} />
但我希望能够在我的文本区域中使用标记/降价标签,然后在发布帖子时获得输出。 例如:
# Hello there,> I want to be able to make mytext area be able to take this and then output markdown style body.
你好,
我希望能够让 mytext 区域能够接受这个然后输出 Markdown 样式的正文。
解决方法
我建议使用库来协助降价。我以前用过这个,效果很好:https://uiwjs.github.io/react-md-editor/
安装:npm i @uiw/react-md-editor
导入反应:import MEditor from "@uiw/react-md-editor";
然后只需使用 MEditor 和 MEditor.markdown 组件来输入和显示您的 Markdown。
文档中有更多信息,请阅读https://uiwjs.github.io/react-md-editor/
,请试试这个代码,到如何使文本区域采用降价属性 (HTML)。
<form>
<input name="title" type="text" placeholder="Title?" />
<textarea name="content" data-provide="markdown" rows="10"></textarea>
<label class="checkbox">
<input name="publish" type="checkbox"> Publish
</label>
<hr/>
<button type="submit" class="btn">Submit</button>
</form>
希望此代码对您有用。
谢谢。
,我在大多数项目中使用 react-markdown-editor-lite。
// import react,react-markdown-editor-lite,and a markdown parser you like
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import MarkdownIt from 'markdown-it'
import MdEditor from 'react-markdown-editor-lite'
// import style manually
import 'react-markdown-editor-lite/lib/index.css';
// Register plugins if required
// MdEditor.use(YOUR_PLUGINS_HERE);
// Initialize a markdown parser
const mdParser = new MarkdownIt(/* Markdown-it options */);
// Finish!
function handleEditorChange({html,text}) {
console.log('handleEditorChange',html,text)
//You can use the text props to save it to your database
}
export default (props) => {
return (
<MdEditor
style={{ height: "500px" }}
renderHTML={(text) => mdParser.render(text)}
onChange={handleEditorChange}
/>
)
}
,
我也按照 Croc 的建议使用 @uiw/react-md-editor。 我还建议您处理不受信任的不良行为者/用户可能会滥用的恶意脚本。
不幸的是,这在库文档中没有得到很好的记录,因此您可能希望这样做:
在编辑模式下:
<MDEditor
value={value}
autoFocus={false}
onChange={handleChange}
previewOptions={{ skipHtml: true,escapeHtml: true,transformLinkUri: null,linkTarget: '_blank' }}
/>
在预览/只读模式下:
<MDEditor.Markdown source={value} escapeHtml={true} skipHtml={true} transformLinkUri={null} />