React 所见即所得编辑器 Vditor
前言
在網頁上嵌入一個 Typora 編輯器是不是很酷的一件事?
Markdown是程序員寫文檔最喜歡的語法,但是直接寫Markdown并不夠直觀,所以出現了「所見即所得」的Markdown編輯器,Typora就是拔尖的產品。
我的博客寫作過程是先在 Typora上寫好,然后復制Markdown到博客編輯上進行保存發布。開始使用Markdown編輯器是 for-editor,我之前寫過for-editor富文本組件的使用方法 React富文本——markdown編輯器
但是這個過程太麻煩了,如果有一個富文本組件能夠實現 Markdown所擊即所得的編輯文章,那就完美了。
經過在 GitHub 上搜索,發現了類似的富文本組件 Vditor
成品圖
安裝依賴
NPM
npm install vditor --saveUMD
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vditor/dist/index.css" /> <script src="https://cdn.jsdelivr.net/npm/vditor/dist/index.min.js"></script>初始化編輯器
import React, { useEffect, useRef } from 'react'; import Vditor from 'vditor'; import "vditor/dist/index.css"; import './index.less';interface MarkdownEditorProps {value: string;onChange: (value: string) => void; }export default function MarkdownEditor(props: MarkdownEditorProps) {const { value, onChange } = props;const editorRef = useRef<HTMLDivElement>(null);useEffect(() => {const vditor = new Vditor(editorRef.current,{value,input: (value) => onChange(value),cache: { id: 'vditor' },height: '100%',counter: { enable: true }})}, [])return (<div className="markdown-editor" ref={editorRef}></div>) }【vditor示例圖】
對比之前我使用的純Markdown編輯器for-editor,如果想使用for-editor編輯器,可以參考:React富文本——markdown編輯器
【for-editor示例圖】
vditor詳細配置
Vditor官網地址
附件上傳功能
配置config
let vditor = new Vditor(editorRef.current,{value,input: onChange,cache: { id: 'vditor' },height: '100%',counter: { enable: true },// outline: { enable: true, position: 'right' },upload: {url: 'http://localhost:300/upload',fieldName: 'file',extraData: { packet: 'blog' },format: (files: File[], responseTxt) => {const res = JSON.parse(responseTxt);const name = files[0].name;const url = res.data.url;const result = JSON.stringify({ code: 0, data: { errFiles: '', succMap: { [name]: url } } });return result;},}})一、默認流程
-
采用vditor默認上傳流程,upload必填參數
-
url 填寫處理上傳服務器地址
-
fieldName 是服務器接受附件參數的字段
-
extraData 除了附件參數外額外的參數
-
format 方法講服務器返回值格式化成vditor接受的數據格式(JSON格式)
{ code: 0, data: { errFiles: ‘’, succMap: { [name]: url } } }
-
?
二、自定義上傳
-
通過 handler 方法處理上傳過程,接受 File 參數,返回vditor接受的數據格式
{ code: 0, data: { errFiles: ‘’, succMap: { [name]: url } } }
三、服務器處理
【koa】
ajax圖片上傳功能實現(點擊,拖拽,粘貼)Koa服務端
【Nest】
import {Post,UseInterceptors,UploadedFile, } from '@nestjs/common';@Post('upload')@UseInterceptors(FileInterceptor('file'))async smmsCommon(@UploadedFile() file, @Body() body) {const { packet } = body;const random = uuidv4().replace(/-/g, '');const prefix = file.originalname.split('.').pop().toLowerCase();const targeName = `${random}.${prefix}`;...return {code:0,data:'http://localhost:3000/image.png'} }總結
以上是生活随笔為你收集整理的React 所见即所得编辑器 Vditor的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux sendmail
- 下一篇: 谁也拦不住你