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

时间:2017-02-18 06:16:33

标签: reactjs draftjs

我按CTRL+B =>我希望选中的文字加粗。

有用的链接:

1 个答案:

答案 0 :(得分:3)

我们需要将两个道具传递给<Editor/>
keyBindingFn:将CTRL + some key映射到某些操作刺痛
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.toggleCodeetc

相关问题