import 'braft-editor/dist/index.css'
import BraftEditor from 'braft-editor'
import {ContentUtils} from 'braft-utils'
import React, {Component, Fragment} from 'react';
// 定义输入转换函数
const unitImportFn = (unit, type, source) => {
// type为单位类型,例如font-size等
// source为输入来源,可能值为create或paste
// 此函数的返回结果,需要过滤掉单位,只返回数值
if (unit.indexOf('rem')) {
return parseFloat(unit, 10) * sizeBase
} else {
return parseFloat(unit, 10)
}
};
// 定义输出转换函数
const unitExportFn = (unit, type, target) => {
if (type === 'line-height') {
// 输出行高时不添加单位
return unit
}
// target的值可能是html或者editor,对应输出到html和在编辑器中显示这两个场景
if (target === 'html') {
// 只在将内容输出为html时才进行转换
return unit / sizeBase + 'rem'
} else {
// 在编辑器中显示时,按px单位展示
return unit + 'px'
}
};
class AddArticle extends Component {
state = {
editorState: BraftEditor.createEditorState(null), // 设置编辑器初始内容
}
handleContentChange = (editorState) => {
this.setState({
editorState: editorState,
});
};
uploadHandler = (info) => {
if (!info.file) {
return false
}
if (info.file.status === 'uploading') {
this.setState({loading: true});
return;
}
if (info.file.status === 'done') {
let data = info.file.response;
if (data.code === 200) {
this.setState({
loading: false,
editorState: ContentUtils.insertMedias(this.state.editorState, [{
type: 'IMAGE',
url: info.file.response.data[0]
}])
})
} else {
message.error('图片上传失败');
}
}
};
render() {
const extendControls = [
{
key: 'antd-uploader',
type: 'component',
component: (
<Upload {...props}
onChange={this.uploadHandler}
// customRequest={this.uploadHandler}
>
{/* 这里的按钮最好加上type="button",以避免在表单容器中触发表单提交,用Antd的Button组件则无需如此 */}
<button type="button" className="control-item button upload-button" data-title="插入图片">
<Icon type="picture" theme="filled"/>
</button>
</Upload>
)
}
];
return (
<BraftEditor placeholder="shift+enter实现换行效果"
excludeControls={excludeControls} value={editorState}
// converts={{unitImportFn, unitExportFn}}
extendControls={extendControls}
onBlur={this.handleContentChange}
/>
)
}
}