安裝:
cnpm install -D draft-js draftjs-to-html react-draft-wysiwyg
// 用來指定商品詳情的富文本編輯庫
import React, { Component } from ‘react’
import { EditorState, convertToRaw, ContentState } from ‘draft-js’
import { Editor } from ‘react-draft-wysiwyg’
import draftToHtml from ‘draftjs-to-html’
import htmlToDraft from ‘html-to-draftjs’
import ‘react-draft-wysiwyg/dist/react-draft-wysiwyg.css’
import PropTypes from “prop-types”
class Richtextedit extends Component {
static propTypes = {
detail: PropTypes.string
}
state = {
// 建立一個沒有内容的編輯對象
editorState: EditorState.createEmpty()
}
constructor(props) {
super(props);
const html = this.props.detail;
if(html){
// 如果有值, 根據html格式字元串建立一個對應的編輯對象
const contentBlock = htmlToDraft(html);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
const editorState = EditorState.createWithContent(contentState);
this.state = {
editorState
};
} else {
this.state = {
editorState: EditorState.createEmpty(), // 建立一個沒有内容的編輯對象
}
}
}
}
// 輸入過程中實時的回調
onEditorStateChange = (editorState) => {
this.setState({
editorState,
});
}
getDetail= () => {
// 傳回輸入資料對應的html格式的文本
return draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()))
}
// 富文本中的圖檔上傳
uploadImageCallBack = (file) => {
return new Promise(
(resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('POST', '/manage/img/upload')
const data = new FormData()
data.append('image', file)
xhr.send(data)
xhr.addEventListener('load', () => {
const response = JSON.parse(xhr.responseText)
const url = response.data.url // 得到圖檔的url
resolve({ data: { link: url } })
})
xhr.addEventListener('error', () => {
const error = JSON.parse(xhr.responseText)
reject(error)
})
}
)
}
render() {
const { editorState } = this.state;
return (
)
}
}
export default Richtextedit;
// wysiwyg:what you see is what you get
import Richtextedit from “./Richtextedit”
//擷取富文本的值
const detail = this.refs.detail.getDetail();
//detail中可傳入html格式的字元串,示例如下
// detail = ‘
女士夏季超短裙,價格優惠,哈哈哈哈,是打發斯蒂芬,大所發生的發,11111,333333,阿斯頓發送到發 ,是的發送到發三的\n
\n
\n’
demo
import React, { Component } from ‘react’;
import { EditorState, convertToRaw } from ‘draft-js’;
import { Editor } from ‘react-draft-wysiwyg’;
import draftToHtml from ‘draftjs-to-html’;
import htmlToDraft from ‘html-to-draftjs’;
class EditorConvertToHTML extends Component {
state = {
editorState: EditorState.createEmpty(),
}
onEditorStateChange: Function = (editorState) => {
this.setState({
editorState,
});
};
render() {
const { editorState } = this.state;
return (
);
}
}