如果我想处理字符 *
的输入,我可以使用 handleBeforeInput(str)
:
handleBeforeInput(str) {
if (str !== '*') {
return false;
}
// handling
return true;
}
如果我想处理ENTER
的输入,我可以使用钩子handleReturn(e)
但如果我想处理DELETE
的输入,应该怎么做呢?
如果我想处理字符 *
的输入,我可以使用 handleBeforeInput(str)
:
handleBeforeInput(str) {
if (str !== '*') {
return false;
}
// handling
return true;
}
如果我想处理ENTER
的输入,我可以使用钩子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
/>
import Editor, {getDefaultKeyBinding, KeyBindingUtil} from 'draft-js';
const {hasCommandModifier} = KeyBindingUtil;
class MyEditor extends React.Component {
constructor(props) {
super(props);
this.handleKeyCommand = this.handleKeyCommand.bind(this);
}
// ...
handleKeyCommand(command: string): DraftHandleValue {
if (command === 'enter_command') {
console.log('enter_command');
return 'handled';
}
if (command === 'ctrl_s_command') {
console.log('ctrl_s_command');
return 'handled';
}
return 'not-handled';
}
myKeyBindingFn = (e) => {
if (e.keyCode === 13 /* `enter` key */ ) {
return 'enter_command';
}
if (e.keyCode === 83 /* `S` key */ && hasCommandModifier(e) /* + `Ctrl` key */) {
return 'ctrl_s_command';
}
//else...
return getDefaultKeyBinding(e);
}
render() {
return (
<Editor
editorState={this.state.editorState}
handleKeyCommand={this.handleKeyCommand}
keyBindingFn={myKeyBindingFn}
...
/>
);
}
}
keydown
事件来检测Delete键,如下所示:var input_field = document.getElementById('your_text_field');
input_field.addEventListener('keydown', function () {
if (event.keyCode == 46) { //Here 46 is key-code of "Delete" key
//...your work when delete key pressed..
}
});
希望这对你有用。