ドラフトにコンテンツ全体を取得するにはどうすればよいですか?ドラフトのコンテンツ全体を取得する方法
たとえば、ボタンをクリックしてコンテンツのフォントサイズを変更したいとします。デフォルトはすべてcontentStateです。ユーザーはmacのCMD + Aをクリックする必要はありませんでした。
あなたが全体の内容に選択を設定cmd+A
をクリックすると、私の貧しいEnglish.Thank U.ため
ドラフトにコンテンツ全体を取得するにはどうすればよいですか?ドラフトのコンテンツ全体を取得する方法
たとえば、ボタンをクリックしてコンテンツのフォントサイズを変更したいとします。デフォルトはすべてcontentStateです。ユーザーはmacのCMD + Aをクリックする必要はありませんでした。
あなたが全体の内容に選択を設定cmd+A
をクリックすると、私の貧しいEnglish.Thank U.ため
を許して。ボタンをクリックすると、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);
}