1. 操作自定义block
1.1 添加
const { AtomicBlockUtils } = Draft;
function add() {
const { editorState } = this.state;
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(type, 'MUTABLE' | 'IMMUTABLE', data: Object);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newEditorState = AtomicBlockUtils.insertAtomicBlock(editorState: EditState, entityKey, blockChars: string);
this.setState({ editorState: newEditorState });
}
1.2 修改
function modify() {
const { editorState } = this.state;
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(type, 'MUTABLE' | 'IMMUTABLE', newData: Object);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newContentState = Modifier.applyEntity(contentStateWithEntity, selection, entityKey);
const newEditorState = EditorState.push(editorState, newContentState, 'apply-entity');
this.setState({ editorState: newEditorState });
}
2. 移动光标
2.1 移动到指定位置(好像对自定义block的光标移动无效)
const { editorState } = this.state;
const oldSelectionState = editorState.getSelection();
const newSelectionState = oldSelectionState.merge({ anchorOffset: 0, focusOffset: 2})) });
this.setState({ editorState: EditorState.forceSelection(editorState, newSelectionState) });
2.2 移动到文章末尾
const { editorState } = this.state;
const newSelectionState = EditorState.moveSelectionToEnd(editorState).getSelection();
this.setState({ editorState: EditorState.forceSelection(editorState, newSelectionState) });
this.setState({ editorState: EditorState.moveSelectionToEnd(editorState) });
3. 插入文本
const { editorState } = this.state;
const newContentState = Modifier.insertText(
editorState.getCurrentContent(),
editorState.getSelection(),
'this is insert text',
OrderedSet.of('BOLD', 'ITALIC')),
);
this.setState({ editorState: EditorState.push(editorState, newContentState, 'insert-characters') })
3.1 创建行内样式
OrderedSet.of('BOLD')
OrderedSet.of('BOLD', 'ITALIC')),
4. entity
4.1 修改entity数据
const newEditorState = EditorState.push(
editorState,
editorState.getCurrentContent().mergeEntityData(entityKey, data)
, 'change-block-data');