作者: 文章来源:
本文原地址:https://www.mimiwuqi.com/webqianduan/197200.html
目录文章目录界面制作好以后,就可以自己制作一个 Markdown 编辑器,这里我设计的也没那么麻烦,只要支持Markdown语法的编写,并且能实时预览就可以。
在function的头部直接声明对应的useState,代码如下(为了以后方便,我们在这里把所有的 useState 都声明出来):
const [articleId,setArticleId] = useState(0) // 文章的 ID,如果是 0 说明是新增加,如果不是 0,说明是修改
const [articleTitle,setArticleTitle] = useState('') //文章标题
const [articleContent , setArticleContent] = useState('') //markdown 的编辑内容
const [markdownContent, setMarkdownContent] = useState('预览内容') //html 内容
const [introducemd,setIntroducemd] = useState() //简介的 markdown 内容
const [introducehtml,setIntroducehtml] = useState('等待编辑') //简介的 html 内容
const [showDate,setShowDate] = useState() //发布日期
const [updateDate,setUpdateDate] = useState() //修改日志的日期
const [typeInfo ,setTypeInfo] = useState([]) // 文章类别信息
const [selectedType,setSelectType] = useState(1) //选择的文章类别
声明完成后需要对 marked 进行基本的设置,这些设置我在之前的教程笔记中已经都讲过,这里就直接给出代码了。
marked.setOptions({
renderer: marked.Renderer(),
gfm: true,
pedantic: false,
sanitize: false,
tables: true,
breaks: false,
smartLists: true,
smartypants: false,
});
实现实时预览非常简单,写两个对应的方法,在onChange事件触发时执行就可以。方法体也只是用marked进行简单的转换,当然对应的 CSS 是我们对应好的。
const changeContent = (e)=>{
setArticleContent(e.target.value)
let html=marked(e.target.value)
setMarkdownContent(html)
}
const changeIntroduce = (e)=>{
setIntroducemd(e.target.value)
let html=marked(e.target.value)
setIntroducehtml(html)
}
<TextArea
value={articleContent}
className="markdown-content"
rows={35}
onChange={changeContent}
onPressEnter={changeContent}
placeholder="文章内容"
/>
<div
className="show-html"
dangerouslySetInnerHTML = {{__html:markdownContent}} >
</div>
<TextArea
rows={4}
value={introducemd}
onChange={changeIntroduce}
onPressEnter={changeIntroduce}
placeholder="文章简介"
/>
<div
className="introduce-html"
dangerouslySetInnerHTML = {{__html:'文章简介:'+introducehtml}} >
</div>
这样就完成了Markdown编辑器的编写,可以到浏览器中预览一下结果了。
更多 建站教程 请访问 https://www.mimiwuqi.com/webqianduan/