偷个懒先贴上两个文档
1.block-render主要用来自定义渲染的,一般是通过css,或者更换标签,当然也可以用自定义组件
在处理粘贴进来的内容时,有着映射,粘贴这块我没试过,render的实验在第2篇中最后那个例子中有。
2.block-component 用来做一些复杂的组件比如多媒体组件和一些有交互事件的组件。
这个就不想洗赘述了,贴上一个多媒体组件的,在2中例子基础上加的,添加了
左中右
对齐(但是有点bug,左中右通过替换标签方式实现的,不是叠加样式,所以标题和对齐冲突),还添加了个图片粘贴功能(图片不能和文本一起粘贴,分开粘贴没问题,一起粘贴图片就被忽略了,直接粘贴文件不知道为何出错,如果有人解决了可以告诉我下,拖放文件没测试成功
###components/MyEditor.jsx
import React from 'react';
import { Editor, EditorState, RichUtils, DefaultDraftBlockRenderMap, AtomicBlockUtils, convertToRaw, Entity, } from 'draft-js';
import Immutable from 'immutable';
import "draft-js/dist/Draft.css";
import styles from './Rich.less'
const blockRenderMap = Immutable.Map({
'header-two': {
element: 'h2',
aliasedElements: ['p'],
},
'left': {
element: 'div',
},
'right': {
element: 'div',
},
'center': {
element: 'div',
},
});
class MyEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
showURLInput: false,
url: '',
urlType: '',
};
this.focus = () => this.refs.editor.focus();
this.logState = () => {
const content = this.state.editorState.getCurrentContent();
console.log(convertToRaw(content));
};
this.onURLChange = (e) => this.setState({ urlValue: e.target.value });
this.addAudio = this._addAudio.bind(this);
this.addImage = this._addImage.bind(this);
this.addVideo = this._addVideo.bind(this);
this.confirmMedia = this._confirmMedia.bind(this);
this.pasteMedia = this._pasteImage.bind(this);
this.onChange = (editorState) => this.setState({ editorState });
this.handleKeyCommand = (command) => this._handleKeyCommand(command);
this.onURLInputKeyDown = this._onURLInputKeyDown.bind(this);
this.onTab = (e) => this._onTab(e);
this.toggleBlockType = (type) => this._toggleBlockType(type);
this.toggleInlineStyle = (style) => this._toggleInlineStyle(style);
}
_handleKeyCommand(command) {
const {editorState} = this.state;
const newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
this.onChange(newState);
return true;
}
return false;
}
_onTab(e) {
const maxDepth = 4;
this.onChange(RichUtils.onTab(e, this.state.editorState, maxDepth));
}
_toggleBlockType(blockType) {
this.onChange(
RichUtils.toggleBlockType(
this.state.editorState,
blockType
)
);
}
_toggleInlineStyle(inlineStyle) {
this.onChange(
RichUtils.toggleInlineStyle(
this.state.editorState,