2

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

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

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

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

4

3 回答 3

24

Draft 的 Editor 组件采用一个名为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 组件,如下所示:

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

您可以在 Draft docs 中阅读有关它的更多信息。

于 2016-12-05T16:03:46.903 回答
3

在 Draft-js 版本 ^0.11.7 中执行此操作的方法是:

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}
        ...
      />
    );
  }
}
于 2020-09-15T10:43:38.667 回答
-2

Delete您可以使用 JavaScript 的事件检测密钥keydown,如下所示:

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..
    }
});

希望,你需要这个。

于 2016-12-04T10:32:55.667 回答