javascript - Draft js中如何处理按键事件

标签 javascript keyboard-events draftjs

如果我想处理字符*的输入,我可以使用handleBeforeInput(str):

handleBeforeInput(str) {
    if (str !== '*') {
      return false;
    }
    // handling
    return true;
}

如果我想处理ENTER的输入,我可以使用钩子(Hook)handleReturn(e)

但是如果我想处理DELETE的输入,该怎么办?

最佳答案

Draft 的编辑器组件采用名为 keyBindingFn 的可选属性。如果您为其分配一个函数,该函数将接收所有 keyDown 事件。理论上,您可以在此函数中执行任何您想要的操作,但它的责任实际上是返回一个字符串类型的命令,该命令应该针对特定键(或键组合)执行。它可能看起来像这样:

function keyBindingFn(e) {
  if (e.key === 'Delete') {
    return 'delete-me' // name this whatever you want
  }

  // This wasn't the delete key, so we return Draft's default command for this key
  return Draft.getDefaultKeyBinding(e)
}

Editor 组件还采用另一个名为 handleKeyCommand 的可选属性。如果为此分配了一个功能,它将接收在编辑器中执行的所有命令。这意味着,如果您使用上面的示例,每当按下删除键时,它都会收到命令“delete-me”。这是处理该命令的地方。

function handleKeyCommand(command) {
  if (command === 'delete-me') {
    // Do what you want to here, then tell Draft that we've taken care of this command
    return 'handled'
  }

  // This wasn't the 'delete-me' command, so we want Draft to handle it instead. 
  // We do this by telling Draft we haven't handled it. 
  return 'not-handled'
}

为了澄清,您可以将这些函数传递给编辑器组件,如下所示:

<Editor 
  keyBindingFn={keyBindingFn}
  handleKeyCommand={handleKeyCommand}
  ... // other props
/>

您可以阅读更多相关信息 in the Draft docs .

关于javascript - Draft js中如何处理按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40955840/

相关文章:

javascript - Typescript - 在文本框中输入文本时使用替换列表进行验证

javascript - 循环遍历所有定义的jquery变量

javascript - js Promise,取消超时

javascript - 如何停止循环数组的方法?

java - 同时使用按键事件和鼠标事件

javascript - React 控制内容可编辑

c# - 在 mac sierra 上捕获并更改键盘以模拟 neo2 键盘布局

javascript - 如何在 IE 和 PhantomJS 中使用 Typescript 创建 KeyboardEvent

javascript - JS 草案 - 提及 - 插件产生此 : Warning: React does not recognize the isFocused prop on a DOM element

javascript - Draft-js 编辑器导致反向输入