How to create custom key bindings in draft.js?

大憨熊 提交于 2020-12-12 05:51:05

问题


I press CTRL+B => I want selected text bolded.


Useful links:

  • http://facebook.github.io/draft-js/docs/advanced-topics-key-bindings.html#content - describes what keyBindingFn and handleKeyCommand do.

  • https://github.com/facebook/draft-js/blob/master/examples/draft-0-10-0/rich/rich.html - lengthy example.

  • https://www.youtube.com/watch?v=0k9suXgCtTA - great video explaining how to add a button that will toggle boldness.

回答1:


We need to pass two props to our <Editor/>:
keyBindingFn: maps CTRL + some key to some action sting
handleKeyCommand: gets passed this action string and decides what to do with it.

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}
    />
}

If you want something other than inline bold text (RichUtils.toggleInlineStyle), you can use RichUtils.toggleBlockType, RichUtils.toggleCode, etc.



来源:https://stackoverflow.com/questions/42311815/how-to-create-custom-key-bindings-in-draft-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!