如何在Draft.js中处理按键事件

4

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

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

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

但如果我想处理DELETE的输入,应该怎么做呢?


请提供需要翻译的内容。 - Naman
3个回答

26

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组件:
<Editor 
  keyBindingFn={keyBindingFn}
  handleKeyCommand={handleKeyCommand}
  ... // other props
/>

你可以在Draft文档中阅读更多相关信息

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

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

希望这对你有用。


非常感谢!但我想知道在草稿的生命周期中是否有处理删除的方法。 - Jonas Hao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接