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

我们接着上一节的示例内容,现在有如下需求,我们希望当我们按下某个按键时编辑器有所反应。这就需要我们对编辑器添加事件功能onKeyDown, 我们给 Editor添加事件:

SDocor.jsx

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

import { initialValue } from './_configure';

function SDocer() {
  const [editor] = useState(() => withReact(createEditor()));

  return (
    <Slate editor={editor} initialValue={initialValue}>
      <Editable
        onKeyDown={event => {
          console.log(event.key)
        }}
      />
    </Slate>
  )
}

export default SDocer;

现在看控制台的打印结果,能捕获到每一次的按键值。当然这肯定不是我们想要的,我们想要的是有一个实用的功能。比如,当按下 &键时在文本中插入 and单词。修改如下:

SDocer.jsx

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

import { initialValue } from './_configure';

function SDocer() {
  const [editor] = useState(() => withReact(createEditor()));

  return (
    <Slate editor={editor} initialValue={initialValue}>
      <Editable
        onKeyDown={event => {
          console.log(event.key)
          if (event.key === '&') {
            event.preventDefault()
            editor.insertText('and')
          }
        }}
      />
    </Slate>
  )
}

export default SDocer;

当我们键入 &时就能看到界面上的变化了。有点意思是不是。

相关推荐
阿蒙Amon7 分钟前
JavaScript学习笔记:6.表达式和运算符
javascript·笔记·学习
hashiqimiya29 分钟前
两个步骤,打包war,tomcat使用war包
java·服务器·前端
小a杰.44 分钟前
Flutter 设计系统构建指南
开发语言·javascript·ecmascript
零度@1 小时前
Java中Map的多种用法
java·前端·python
yuanyxh1 小时前
静默打印程序实现
前端·react.js·electron
三十_A3 小时前
如何正确实现圆角渐变边框?为什么 border-radius 对 border-image 不生效?
前端·css·css3
kgduu3 小时前
js之事件系统
javascript
小满zs3 小时前
Next.js第十三章(缓存组件)
前端
前端老宋Running3 小时前
“受控组件”的诅咒:为什么你需要 React Hook Form + Zod 来拯救你的键盘?
前端·javascript·react.js
风止何安啊3 小时前
拿捏 React 组件通讯:从父子到跨组件的「传功秘籍」
前端·react.js·面试