はじめに
convertFromHTMLでは一部のインラインスタイルにしか対応しておらず、フォントカラーが復元されないという問題があります。
html-to-draftjsがフォントカラーなどのInlineStylesの復元に対応しているので軽く使ってみようと思います。
行程は以下の通りです。
- htmlToDraftを使ってhtmlを変換し、editorStateを作成する
- color-〇〇の名前でInlineStyleを作成、styleMapに追加する
- 1と2で作成したeditorStateとstyleMapをEditorにセットする
1.htmlToDraftを使ってhtmlを変換し、editorStateを作成する
const html = `<span style="color:rgb(0,128,0)">te</span><span style="color:red">st</span>`;
const htmlToEState = (html:string) =>{
const blockArray = htmlToDraft(html);
const contentState = ContentState.createFromBlockArray(blockArray.contentBlocks, blockArray.entityMap);
const editorState = EditorState.createWithContent(contentState);
return editorState;
}
2.color-〇〇の名前でInlineStyleを作成、styleMapに追加する
htmlToDraftでは'color-'とhtmlElementのcolorにある値を結合して、InlineStyleをセットします。colorには'red'で値がはいるので'color-Red'と定義したら色が変わらなくなるので注意してください。rgbでの定義にも対応しています。
const styleMap = {
'color-red':{ 'color':'red'},
'color-rgb(0,128,0)':{ 'color':'rgb(0,128,0)'}
}
3. 1と2で作成したeditorStateとstyleMapをEditorにセットする
const RichTextEditor = () => {
const [ editorState, setEditorState ] = useState(htmlToEState(html));
return(
<Editor customStyleMap={styleMap} editorState={editorState} onChange={setEditorState}/>
);
}
テキストの表示
最後に
htmltodraftでは背景色、フォントサイズ、フォントファミリーにも対応しているので使ってみてください。
InlineStyle名はそれぞれ、bgcolor-〇〇、fontsize-〇〇(例:smallもしくは12)、fontfamily-(例: MS PGothic)
styleMap例
const styleMap = {
'fontfamily-MS Mincho':{ 'fontFamily':'MS Mincho'},
'bgcolor-red':{ 'backgroundColor':'red'},
'fontsize-32':{'fontSize':'32px'}
}