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

时间:2016-12-04 05:51:05

标签: javascript keyboard-events draftjs

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

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

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

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

2 个答案:

答案 0 :(得分:0)

您可以使用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..
    }
});

希望,你需要这个。

答案 1 :(得分:0)

在草稿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}
        ...
      />
    );
  }
}