如果我想处理字符*
的输入,我可以使用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/