Draft.jsで独自のblock(独自コンポーネント)を作る方法です。
やり方は2種類あります。
CustomBlockを使う方法とAtomicBlockを使う方法です。
公式では、後者のやり方が書かれていますが、数が少ないならそれでもよいのですが、数が増えてくると煩雑になるので前者のほうをおすすめします。
CustomBlockを使う方法
画像を表示する独自blockを作る例で説明します。
CustomBlockを定義
export default class ImageBlock extends Component {
render() {
return (
<img
src={this.props.blockProps.src}
/>
);
}
}
props.blockPropsから下記blockRendererでセットしたプロパティを取得できます。
Editorに独自のblockRendererを登録
<Editor
...
blockRenderFn={this.blockRenderer}
/>
blockRenderer = block => {
switch (block.type) {
case 'IMAGE':
const src = block.getData().get('src');
return {
component: ImageBlock,
props: {
src: src,
},
};
CustomBlockの使い方
const newEditorState = insertNewBlock(
this.state.editorState,
'IMAGE',
{src: 'http://example.com'},
);
this.setState({
editorState: newEditorState,
});
AtomicBlockを使う方法
こちらも同様に画像を表示する独自blockを作る例で説明します。
export default class CustomAtomicBlock extends Component {
render() {
let entityKey = this.props.block.getEntityAt(0);
const entity = this.props.contentState.getEntity(entityKey);
const {src} = entity.getData();
const type = entity.getType();
switch (type) {
case 'image':
return <img src={src} />;
Editorに独自のblockRendererを登録
<Editor
...
blockRenderFn={this.blockRenderer}
/>
blockRenderer = block => {
switch (block.type) {
case 'atomic':
const src = block.getData().get('src');
return {
component: CustomAtomicBlock,
props: {
src: src,
},
};
AtomicBlockの挿入
const contentState = this.state.editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
'image',
'IMMUTABLE',
{src: 'http://example.com'},
);
let newEditorState = EditorState.set(this.state.editorState, {
currentContent: contentStateWithEntity,
});
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
newEditorState = AtomicBlockUtils.insertAtomicBlock(
newEditorState,
entityKey,
' ',
);