markdown编辑器和展示

767 阅读1分钟

前言:学习这个是为了编写博客系统做准备,完全去编写一个 markdown 编辑器,在目前的环境下不是特别必要,所以只是简单的使用

涉及文档

  1. for-editor:一个 markdown 编辑器作为到时的编辑
  2. react-markdown:用作展示 markdown 语法后的代码

需要下载的依赖

yarn add react-markdown remark-gfm for-editor react-syntax-highlighter

使用编辑器

import React from 'react';
import Editor from 'for-editor';

const toolbar = {
    h1: true, // h1
    h2: true, // h2
    h3: true, // h3
    h4: true, // h4
    img: true, // 图片
    link: true, // 链接
    code: true, // 代码块
    undo: true, // 撤销
    redo: true, // 重做
    save: true, // 保存
    preview: true, // 预览
    expand: true, // 全屏
    subfield: true, // 单双栏模式
}

export default function Index() {
    const [value, setValue] = React.useState('');
    
    const handleChange = (v) => {
        setValue(v);
    }
    
    return (
        <div>
            <Editor
                value={value}
                onChange={handleChange}
                toolbar={toolbar}
            />
        </div>
    );
}

进行展示

import React from 'react';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm'; // 对一些无法直接解析的用插件
// 高亮
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/esm/styles/prism';

// 处理一些节点
const components = {
    code({ node, inline, className, children, ...props }) {
        const match = /language-(\w+)/.exec(className || '');
        return !inline && match) ? (
            <SyntaxHighlighter style={dark} language={match[1]} PreTag="div" children={String(children).replace(/\n$/, '')} {...props} />
        ) : (
            <code className={className} {...props}>
                {children}
            </code>
        )
    }
}

export default function Index() {
    const [value, setValue] = React.useState('');
    
    return (
        <div>
            <ReactMarkdown
                components={components}
                remarkPlugins={[gfm]}
                children={value}
            />
        </div>
    );
}