React集成Draft富文本
import React, {Component} from 'react';
import {Editor} from 'react-draft-wysiwyg';
import {ContentState, convertToRaw, EditorState} from 'draft-js';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import draftToHtml from "draftjs-to-html"
import htmlToDraft from 'html-to-draftjs';
// Draft 富文本编辑器
class Draft extends Component {
constructor(props) {
super(props);
const html = this.props.value;
let editorSta;
if (html) {
// 如果有值, 根据html格式字符串创建一个对应的编辑对象
const contentBlock = htmlToDraft(html);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
editorSta = EditorState.createWithContent(contentState);
} else {
editorSta = EditorState.createEmpty();
}
}
this.state = {
editorState: editorSta,
contentEdit: ''
}
}
// draft 转 html
transformDraftStateToHtml(editorState) {
if (!editorState.getCurrentContent) {
return '';
}
return draftToHtml(convertToRaw(editorState.getCurrentContent()));
};
editorStateChange(editorState) {
this.setState({editorState: editorState})
let transdata = this.transformDraftStateToHtml(editorState);
this.props.onChange(transdata);
this.setState({contentEdit: transdata});
}
contentStateChange(editorState) {
}
render() {
return (
<Editor editorState={this.state.editorState} onEditorStateChange={this.editorStateChange.bind(this)}
onContentStateChange={this.contentStateChange.bind(this)}/>
)
}
}
export default Draft