前提条件
create-react-appを使って環境構築しています。
参考リンク
以下の記事を参考に、というかほぼパクらせてもらいました。ですので、この記事は自分用の備忘録にすぎないです。詳しくは以下のサイトをみてください。
https://qiita.com/mottox2/items/9534f8efb4b09093a304
https://qiita.com/tk1024/items/8d8de5a62ef55bc1532f
Documentの方もだいたい目を通しました。
https://draftjs.org/docs/overview.html#content
コード
RichEditor.jsx
import React, { Component } from 'react';
import {Editor, EditorState, RichUtils} from 'draft-js';
import {stateToHTML} from 'draft-js-export-html';
class RichEditor extends Component {
constructor(props) {
super(props);
this.state = {editorState: EditorState.createEmpty()};
this.onChange = (editorState) => this.setState({editorState});
}
handleKeyCommand(command) {
const newState = RichUtils.handleKeyCommand(this.state.editorState, command)
if (newState) {
this.onChange(newState)
return true
}
return false
}
render() {
return (
<div className='richEditor'>
<h1>Draft.js example</h1>
<button onMouseDown={(e) => {
this.onChange(
RichUtils.toggleInlineStyle(this.state.editorState, 'BOLD')
)
e.preventDefault()
}}>Bold</button>
<button onMouseDown={(e) => {
this.onChange(
RichUtils.toggleInlineStyle(this.state.editorState, 'ITALIC')
)
e.preventDefault()
}}>Italic</button>
<button onMouseDown={(e) => {
this.onChange(
RichUtils.toggleInlineStyle(this.state.editorState, 'UNDERLINE')
)
e.preventDefault()
}}>Underline</button>
<button onMouseDown={(e) => {
this.onChange(
RichUtils.toggleBlockType(this.state.editorState, 'header-one')
)
e.preventDefault()
}}>見出し1</button>
<button onMouseDown={(e) => {
this.onChange(
RichUtils.toggleBlockType(this.state.editorState, 'header-two')
)
e.preventDefault()
}}>見出し2</button>
<button onMouseDown={(e) => {
this.onChange(
RichUtils.toggleBlockType(this.state.editorState, 'unordered-list-item')
)
e.preventDefault()
}}>List</button>
<Editor
editorState={this.state.editorState}
onChange={this.onChange.bind(this)}
handleKeyCommand={this.handleKeyCommand.bind(this)}
/>
<h1>HTML変換</h1>
{stateToHTML(this.state.editorState.getCurrentContent())}
</div>
);
}
}
export default RichEditor
簡単に説明すると、draft-jsのEditorコンポーネントにeditorStateという独自のobjectを持たせることでeditorとして動きます。
また、RichUtilsでRichEditorの真骨頂であるstyle変更が可能になります。
また、draft-js-export-htmlというパッケージを使ってeditorStateをhtmlに変換しています。これをすることで
、バックエンドとの連携もうまくいきそうです。
コード全体はこちら
今後の課題
写真入りの記事を編集できるようにしたいので、draft-js-pluginsを使って
みたいです。