React富文本编辑器开发(四)

上一节我们做了块级元素的格式操作,这节我们来讲行内元素的相关操作。行内元素的样式一般指 粗体斜体代码或 删除线等 。通过前一章的内容得知,元素的渲染是通过渲染器来呈现的,块级元素通过指定 renderElement, 行内元素(即内联元素)在 Slate中也叫 叶子,通过指定 renderLeaf来渲染。即然叶子也是元素,那么就要设计样式。我们来设计一个粗体组件。创建一个新文件,将所有叶子组件放在这里

_leaf.jsx

javascript 复制代码
export const Leaf = ({ attributes, children, leaf }) => {
    if (leaf.bold) {
        children = <strong>{children}</strong>
    }

    if (leaf.code) {
        children = <code>{children}</code>
    }

    if (leaf.italic) {
        children = <em>{children}</em>
    }

    if (leaf.underline) {
        children = <u>{children}</u>
    }

    return <span {...attributes}>{children}</span>
}

当然还要有渲染器,同样我们把叶子的渲染器也独立出来,创建一个文件,如下所示:

_leafRender.jsx

javascript 复制代码
import React from 'react'
import { Leaf } from './_leaf'

export const renderLeaf = props => {
    return <Leaf {...props} />
};

我们把上一节的块元素的渲染器也独立出来:

_elementRender.jsx

javascript 复制代码
import React from 'react';
import { CodeElement, DefaultElement } from './_elements';

export const renderElement = props => {
    switch (props.element.type) {
        case 'code':
            return <CodeElement {...props} />
        default:
            return <DefaultElement {...props} />
    }
};

那么,现在我们的SDocer看起来应该是这样的:

SDocer.jsx

javascript 复制代码
import { useState, useCallback} from 'react';
import { createEditor, Editor, Transforms, Element } from 'slate';
import { Slate, withReact, Editable } from 'slate-react';

import { initialValue } from './_configure';
import { renderElement } from './_elementRender';
import { renderLeaf } from './_leafRender';

function SDocer() {
  const [editor] = useState(() => withReact(createEditor()));
  return (
    <Slate editor={editor} initialValue={initialValue}>
      <Editable
        renderElement={useCallback(renderElement, [])}
        renderLeaf={useCallback(renderLeaf, [])}
        onKeyDown={event => {
          if (!event.ctrlKey) return;
          
          if (event.key === '`') {
            event.preventDefault()

            const [match] = Editor.nodes(editor, {
              match: n => n.type === 'code',
            })

            Transforms.setNodes(
              editor,
              { type: match ? 'paragraph' : 'code' },
              { match: n => Element.isElement(n) && Editor.isBlock(editor, n) }
            )
          }
        }}
      />
    </Slate>
  )
}

export default SDocer;

我们对初始数据做一点调整,如下:

_configrue.jsx

javascript 复制代码
export const initialValue = [
    {
        type: 'paragraph',
        children: [{ text: '这是一行段落文字,内容很少,但很重要!!' }],
    },

    {
        type: 'code',
        children: [{ text: '这是一代码行段落文字,内容很少,但很重要!!' }],
    },

    {
        type: 'paragraph',
        children: [
            { text: 'This is editable ' },
            { text: 'rich', bold: true },
            { text: ' text, ' },
            { text: 'much', italic: true },
            { text: ' better than a ' },
            { text: '<textarea>', code: true, underline: true},
          	{ text: '<textarea>', underline: true},
            { text: '!' },
        ],
    },
];

我们再增加一个功能,当按 ctrl + b时将所选择的内容变成粗体,修改onKeyDown事件,如下所示:

javascript 复制代码
import { useState, useCallback } from 'react';
import { createEditor, Editor, Transforms, Element } from 'slate';
import { Slate, withReact, Editable } from 'slate-react';

import { initialValue } from './_configure';
import { renderElement } from './_elementRender';
import { renderLeaf } from './_leafRender';

function SDocer() {
  const [editor] = useState(() => withReact(createEditor()));
  return (
    <Slate editor={editor} initialValue={initialValue}>
      <Editable
        renderElement={useCallback(renderElement, [])}
        renderLeaf={useCallback(renderLeaf, [])}
        onKeyDown={event => {
          if (!event.ctrlKey) return;

          switch (event.key) {
            case '`': {
              event.preventDefault()
              const [match] = Editor.nodes(editor, {
                match: n => n.type === 'code',
              })
              
              Transforms.setNodes(
                editor,
                { type: match ? 'paragraph' : 'code' },
                { match: n => Element.isElement(n) && Editor.isBlock(editor, n) }
              )
              break
            }

            case 'b': {
              event.preventDefault()
              Editor.addMark(editor, 'bold', true)
              break
            }
          }
        }}
      />
    </Slate>
  )
}

export default SDocer;

瞧,我们的功能越来越多是不是。

相关推荐
葡萄糖o_o几秒前
ResizeObserver的错误
前端·javascript·html
AntBlack2 分钟前
Python : AI 太牛了 ,撸了两个 Markdown 阅读器 ,谈谈使用感受
前端·人工智能·后端
大咖分享课5 分钟前
App跨平台技术2025年深度解析:核心原理与最佳实践
系统架构·前端框架·移动开发·app开发
MK-mm20 分钟前
CSS盒子 flex弹性布局
前端·css·html
小小小小宇33 分钟前
CSP的使用
前端
sunbyte33 分钟前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | AnimatedNavigation(动态导航)
前端·javascript·vue.js·tailwindcss
ifanatic43 分钟前
[每周一更]-(第147期):使用 Go 语言实现 JSON Web Token (JWT)
前端·golang·json
烛阴44 分钟前
深入浅出地理解Python元类【从入门到精通】
前端·python
米粒宝的爸爸1 小时前
uniapp中vue3 ,uview-plus使用!
前端·vue.js·uni-app
JustHappy1 小时前
啥是Hooks?为啥要用Hooks?Hooks该怎么用?像是Vue中的什么?React Hooks的使用姿势(下)
前端·javascript·react.js