2017-10-23 6 views
2

ドラフトにコンテンツ全体を取得するにはどうすればよいですか?ドラフトのコンテンツ全体を取得する方法

たとえば、ボタンをクリックしてコンテンツのフォントサイズを変更したいとします。デフォルトはすべてcontentStateです。ユーザーはmacのCMD + Aをクリックする必要はありませんでした。

あなたが全体の内容に選択を設定cmd+Aをクリックすると、私の貧しいEnglish.Thank U.ため

答えて

1

を許して。ボタンをクリックすると、draft.js SelectionStateでプログラム的に行うことができます。この実例を実際に見てみよう - https://jsfiddle.net/k7wghwuj/1/

いくつかの説明。スタイルを指定する前に、適用するスタイルを指定してください。たとえば、最初の赤い背景と2番目の大きなフォントサイズ(26ピクセル)の2つのスタイルを作成します。 customStyleMapオブジェクトを定義します。このオブジェクトのキーは、カスタムスタイルと値の固有の名前(適切なスタイルのオブジェクト)でなければなりません。

const customStyleMap = { 
    redBackground: { 
    backgroundColor: 'red' 
    }, 
    largeText: { 
    fontSize: 26 
    }, 
}; 

エディタコンポーネントのcustomStyleMapプロパティにこのオブジェクトを渡します。

<Editor 
    placeholder="Type away :)" 
    editorState={this.state.editorState} 
    onChange={this._handleChange} 
    customStyleMap={customStyleMap} 
/> 

onClickハンドラ関数を追加します。最初の引数として適切なスタイルの名前を渡します。 applyStyleOnWholeContentインサイド

<button onClick={() => this.applyStyleOnWholeContent('redBackground')}> 
    set red background for whole content 
</button> 
<button onClick={() => this.applyStyleOnWholeContent('largeText')}> 
    set large font size for whole content 
</button> 

は、最初と最後のContentBlockと、プログラムnew SelectionStateコンストラクタで選択範囲を設定を取得する必要があります。その後

applyStyleOnWholeContent = (styleName) => { 
    const editorState = this.state.editorState; 
    let currentContent = this.state.editorState.getCurrentContent(); 
    const firstBlock = currentContent.getBlockMap().first(); 
    const lastBlock = currentContent.getBlockMap().last(); 
    const firstBlockKey = firstBlock.getKey(); 
    const lastBlockKey = lastBlock.getKey(); 
    const lengthOfLastBlock = lastBlock.getLength(); 

    let newSelection = new SelectionState({ 
    anchorKey: firstBlockKey, 
    anchorOffset: 0, 
    focusKey: lastBlockKey, 
    focusOffset: lengthOfLastBlock 
    }); 
    ... 

Modifier.applyInlineStyleであなたは、EditorStateを更新し、新しい コンテンツの状態を生成する選択をリセットし、変更内容を適用する必要があります。

... 
    currentContent = Modifier.applyInlineStyle(
    currentContent, 
    newSelection, 
    styleName, 
) 

    let newEditorState = EditorState.push(
    editorState, 
    currentContent, 
) 

    newSelection = new SelectionState({ 
    anchorKey: 0, 
    anchorOffset: 0, 
    focusKey: 0, 
    focusOffset: 0 
    }); 

    newEditorState = EditorState.forceSelection(newEditorState, newSelection); 

    this._handleChange(newEditorState); 
} 
関連する問題