如何在draft.js中创建自定义按键绑定?

3
1个回答

12
我们需要向我们的<Editor/>传递两个属性:
keyBindingFn:将CTRL +某些键映射到一些操作字符串
handleKeyCommand:获取此操作字符串并决定对其采取什么行动。
import React from 'react';

import {
  Editor, EditorState,
  RichUtils, getDefaultKeyBinding
} from 'draft-js';


class Problem extends React.Component {
  constructor(props) {
    super(props);
    this.state = { editorState: EditorState.createEmpty() };
  }

  // this function maps keys we press to strings that represent some action (eg 'undo', or 'underline')
  // then the this.handleKeyCommand('underline') function gets called with this string.
  keyBindingFn = (event) => {
    // we press CTRL + K => return 'bbbold'
    // we use hasCommandModifier instead of checking for CTRL keyCode because different OSs have different command keys
    if (KeyBindingUtil.hasCommandModifier(event) && event.keyCode === 75) { return 'bbbold'; }
    // manages usual things, like:
    // Ctrl+Z => return 'undo'
    return getDefaultKeyBinding(event);
  }

  // command: string returned from this.keyBidingFn(event)
  // if this function returns 'handled' string, all ends here.
  // if it return 'not-handled', handling of :command will be delegated to Editor's default handling.
  handleKeyCommand = (command) => {
    let newState;
    if (command === 'bbbold') {
      newState = RichUtils.toggleInlineStyle(this.state.editorState, 'BOLD');
    }

    if (newState) {
      this.setState({ editorState: newState });
      return 'handled';
    }
    return 'not-handled';
  }

  render = () =>
    <Editor
      editorState={this.state.editorState}
      onChange={(newState) => this.setState({ editorState: newState })}
      handleKeyCommand={this.handleKeyCommand}
      keyBindingFn={this.keyBindingFn}
    />
}

如果你想要的不仅仅是内联加粗文本(RichUtils.toggleInlineStyle),你可以使用 RichUtils.toggleBlockTypeRichUtils.toggleCode等等


很好的回答,但我相信默认的 keyBindingFn 已经处理了这种情况。 - natnai
@natnai,正确的做法是将其更改为 CTRL+K => 'bbbold' 以避免混淆。 - Evgenia Karunus

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