gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:05:14 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com