2017-02-18 3 views
1

私はCTRL+Bを押す=>選択したテキストを太字にしたい。draft.jsでカスタムキーバインディングを作成するには?


便利なリンク:

答えて

2

私たちは<Editor/>に2つの小道具を渡す必要があります。
keyBindingFn
handleKeyCommandを刺す一部アクションにマップCTRL + some key:このアクション文字列を渡され、それをどのように処理するかを決定します。

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を使用することができます。

+0

良い答えですが、私はデフォルトの 'keyBindingFn'がすでにこのユースケースを処理していると思います。 – natnai

+0

@natnai、true。混乱を避けるために 'CTRL + K => 'bbbold''に変更しました。 – lakesare

関連する問題