1.首先安装braft-editor
npm install braft-editor
2.添加富文本框
<Form.Item label="内容" name="content" rules={[{ required: true, message: '请输入内容!' }]} > <BraftEditor value={BraftEditor.createEditorState(null)} onChange={this.handleChange} controls={controls} extendControls={extendControls} placeholder="请输入正文内容" /> </Form.Item>
3.添加富文本框功能按钮 其中extendControls是上传图片的按钮,
const controls = [ 'undo', 'redo', 'separator', 'font-size', 'line-height', 'letter-spacing', 'separator', 'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator', 'headings', 'list-ul', 'list-ol', 'separator', 'link', 'separator', 'hr', 'separator', //'media', 'separator' ]; const extendControls = [ { key: 'antd-uploader', type: 'component', component: ( <Upload accept="image/*" showUploadList={false} beforeUpload={this.beforeUploadControls}> {/* 这里的按钮最好加上type="button",以避免在表单容器中触发表单提交,用Antd的Button组件则无需如此 */} <button type="button" className="control-item button upload-button" data-title="插入图片" > <UploadOutlined /> </button> </Upload> ) } ];
4.上传的图片和富文本框的内容保存在form表单中,需借助braft-utils组件
npm install braft-utils
//上传富文本图片 beforeUploadControls = (file) => { console.log('file', file); const index = file.name.lastIndexOf('.'); const isType = file.name.substr(index + 1).toLowerCase(); if (isType !== 'jpg' && isType !== 'png') { message.error('只支持上传jpg和png格式的图片'); return true; } else { if (file.size / (1024 * 1024) > 10 || !file.size) { message.error('上传文件不能为空或超过10M'); } else { let formData = new FormData(); formData.append('file', file); //调用后端接口获取图片链接,formData为参数,resouceUpload为自己封装的方法,需换成自己的 resouceUpload(formData).then((res) => { console.log(res); if (res.data.code == '0') { console.log(this.formRef.current.getFieldValue('content')); console.log(ContentUtils); if (this.formRef.current.getFieldValue('content')) { this.formRef.current.setFieldsValue({ content: ContentUtils.insertMedias(this.formRef.current.getFieldValue('content'), [ { type: 'IMAGE', url: 后端返回的图片的链接 } ]) }); } else { this.formRef.current.setFieldsValue({ content: ContentUtils.insertMedias(BraftEditor.createEditorState(null), [ { type: 'IMAGE', url: 后端返回的图片的链接 } ]) }); } } else { message.error(res.data.message); } }); } } };
//获取富文本框的内容
handleChange = (editorState) => {
const htmlString = editorState.toHTML();
this.setState({
editorState: editorState,
richtext: htmlString
});
};
5.引入文件如下
import { Button, Form, Input, InputNumber, Upload, } from 'antd'; import { UploadOutlined} from '@ant-design/icons'; import BraftEditor from 'braft-editor'; import { ContentUtils } from 'braft-utils'; import 'braft-editor/dist/index.css';