如何在草稿js中处理关键事件

Jon*_*Hao 0 javascript keyboard-events draftjs

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

handleBeforeInput(str) {
    if (str !== '*') {
      return false;
    }
    // handling
    return true;
}
Run Code Online (Sandbox Code Playgroud)

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

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

tob*_*sen 19

Draft的Editor组件使用一个名为的可选prop 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)
}
Run Code Online (Sandbox Code Playgroud)

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'
}
Run Code Online (Sandbox Code Playgroud)

为了澄清,您将这些函数传递给Editor组件,如下所示:

<Editor 
  keyBindingFn={keyBindingFn}
  handleKeyCommand={handleKeyCommand}
  ... // other props
/>
Run Code Online (Sandbox Code Playgroud)

您可以在草稿文档中阅读更多相关信息.