本文的示例代码参考braft-editor
目录
DvaJS
cnpm i -g dva-cli
dva -v
# dva-cli version 0.9.2
dva new braft-editor && cd braft-editor
cnpm i
braft-editor
cnpm i --save braft-editor
vim src/routes/IndexPage.js
import React from 'react'
// 引入编辑器组件
import BraftEditor from 'braft-editor'
// 引入编辑器样式
import 'braft-editor/dist/index.css'
export default class EditorDemo extends React.Component {
state = {
// 创建一个空的editorState作为初始值
editorState: BraftEditor.createEditorState(null)
}
async componentDidMount() {
// 假设此处从服务端获取html格式的编辑器内容
const htmlContent = 'Hello World!'
// 使用BraftEditor.createEditorState将html字符串转换为编辑器需要的editorStat
this.setState({
editorState: BraftEditor.createEditorState(htmlContent)
})
}
submitContent = async () => {
// 在编辑器获得焦点时按下ctrl+s会执行此方法
// 编辑器内容提交到服务端之前,可直接调用editorState.toHTML()来获取HTML格式的内容
const htmlContent = this.state.editorState.toHTML()
// const result = await saveEditorContent(htmlContent)
}
handleEditorChange = (editorState) => {
this.setState({ editorState })
}
render() {
const { editorState } = this.state
return (
<div className="my-component">
<BraftEditor
value={editorState}
onChange={this.handleEditorChange}
onSave={this.submitContent}
/>
</div>
)
}
}
- 测试
cnpm start
七牛云
cnpm i --save qiniu-js
vim src/routes/IndexPage.js
import React from 'react'
import * as qiniu from 'qiniu-js'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'
export default class EditorDemo extends React.Component {
state = {
editorState: BraftEditor.createEditorState(null)
}
async componentDidMount() {
const htmlContent = 'Hello World!'
this.setState({
editorState: BraftEditor.createEditorState(htmlContent)
})
}
submitContent = async () => {
// 在编辑器获得焦点时按下ctrl+s会执行此方法
// 编辑器内容提交到服务端之前,可直接调用editorState.toHTML()来获取HTML格式的内容
const htmlContent = this.state.editorState.toHTML()
// const result = await saveEditorContent(htmlContent)
}
handleEditorChange = (editorState) => {
this.setState({ editorState })
}
uploadFn = (param) => {
const token = 'HhUn8qmWzyd2im3VicF18d32zFB14OL142IxJafU:Va2RRYOz2tQXYWVdoJ4dfU92U9c=:eyJzY29wZSI6InN0YXRpYy1pbWFnZSIsImRlYWRsaW5lIjoxNTQ0NDYyMTk1fQ=='
const putExtra = {
}
const config = {
}
const observer = {
next(res) {
param.progress(res.total.percent)
},
error(err) {
param.error({
msg: err.message
})
},
complete(res) {
param.success({
url: 'http://pjid0qjkn.bkt.clouddn.com/' + res.key
})
}
}
qiniu.upload(param.file, param.name, token, putExtra, config).subscribe(observer)
}
render() {
const { editorState } = this.state
return (
<div className="my-component">
<BraftEditor
value={editorState}
onChange={this.handleEditorChange}
onSave={this.submitContent}
media={{ uploadFn: this.uploadFn }}
/>
</div>
)
}
}
- 测试
cnpm start
浏览器打开http://localhost:8000上传图片文件
七牛云存储的上传凭证在线生成
网友评论