2022-10-15 react+react-draft-wysiwyg之富文本编译器安装过程
npm install --save react-draft-wysiwyg
npm install --save draft-js
npm install --save draftjs-to-html
npm install --save html-to-draftjs
完整代码:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
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'
export default class RichTextEditor extends Component {
static propTypes = {
detail: PropTypes.string
}
state = {
editorState: EditorState.createEmpty(),
}
constructor(props) {
super(props)
const html = this.props.detail
if (html) {
const contentBlock = htmlToDraft(html)
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 = () => {
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
resolve({ data: { link: url } })
})
xhr.addEventListener('error', () => {
const error = JSON.parse(xhr.responseText)
reject(error)
})
}
)
}
render() {
const { editorState } = this.state
return (
<Editor
editorState={editorState}
editorStyle={{ border: '1px solid black', minHeight: 200, paddingLeft: 10 }}
onEditorStateChange={this.onEditorStateChange}
toolbar={{
image: { uploadCallback: this.uploadImageCallBack, alt: { present: true, mandatory: true } },
}}
/>
)
}
}
react-draft-wysiwyg官网:https://github.com/jpuri/react-draft-wysiwyg
官网demo:https://jpuri.github.io/react-draft-wysiwyg/#/demo
网友参考资料:http://t.csdn.cn/oWEdO,http://t.csdn.cn/8FyCo
如何把富文本显示出来呢,我需要的在h5端显示,可以用原生js获取指定元素id来设置innerHTML,如果是vue+uniapp,则可以使用rich-text。
这个富文本编译器是facebook出的,好像是16年的时候吧,感觉和react应该挺配的就用了这个。
执行完上面的安装步骤,并引入依赖,你就可以看到编译器的样子了,本文仅是能让编译器显示出来,至于其他功能(如上传图片,保存内容)暂未实现。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧