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;

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

相关推荐
仟濹4 小时前
【HTML】基础学习【数据分析全栈攻略:爬虫+处理+可视化+报告】
大数据·前端·爬虫·数据挖掘·数据分析·html
小小小小宇5 小时前
前端WebWorker笔记总结
前端
小小小小宇5 小时前
前端监控用户停留时长
前端
小小小小宇5 小时前
前端性能监控笔记
前端
烛阴6 小时前
Date-fns教程:现代JavaScript日期处理从入门到精通
前端·javascript
全栈小56 小时前
【前端】Vue3+elementui+ts,TypeScript Promise<string>转string错误解析,习惯性请出DeepSeek来解答
前端·elementui·typescript·vue3·同步异步
穗余6 小时前
NodeJS全栈开发面试题讲解——P6安全与鉴权
前端·sql·xss
小蜜蜂嗡嗡7 小时前
flutter项目迁移空安全
javascript·安全·flutter
穗余7 小时前
NodeJS全栈开发面试题讲解——P2Express / Nest 后端开发
前端·node.js
航Hang*7 小时前
WEBSTORM前端 —— 第3章:移动 Web —— 第4节:移动适配-VM
前端·笔记·edge·less·css3·html5·webstorm