BraftEditor使用小探
最近基于antd 做站内信前端开发,发现易用美观的富文本编辑器,记录使用的过程,希望对你有所帮助。
安装
# 使用npm安装
npm install braft-editor --save
# 使用yarn安装
yarn add braft-editor
review code
import React, { PureComponent } from 'react';
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'
import { Modal, Form, Input, Button } from 'antd';
const FormItem = Form.Item;
@Form.create()
class EditorDemo extends PureComponent {
state = {
editorState: null,
visible: false,
formVals: {}
}
async componentDidMount() {
// 假设此处从服务端获取html格式的编辑器内容
// const htmlContent = await fetchEditorContent()
const htmlContent = {};
// 使用BraftEditor.createEditorState将html字符串转换为编辑器需要的editorState数据
this.setState({
editorState: BraftEditor.createEditorState(htmlContent)
})
}
submitContent = async () => {
// 在编辑器获得焦点时按下ctrl+s会执行此方法
// 编辑器内容提交到服务端之前,可直接调用editorState.toHTML()来获取HTML格式的内容
const htmlContent = this.state.editorState.toHTML()
// const result = this.saveEditorContent(htmlContent)
alert("保存成功" + htmlContent);
}
handleEditorChange = (editorState) => {
this.setState({ editorState })
}
handleEditorVsiible = (flag) => {
this.setState({ visible: !!flag })
}
saveEditorContent = () => {
const htmlContent = this.state.editorState.toHTML()
alert("保存成功" + htmlContent);
}
insertHello = () => {
alert("onclick");
}
add = () => {
// const formVals = { ...fieldsValue };
const { form } = this.props;
const { formVals } = this.state;
form.validateFields((err, fieldsValue) => {
if (err) return;
const formVals = { ...fieldsValue };
console.log(formVals);
const htmlContent = this.state.editorState.toHTML()
console.log(htmlContent)
});
}
openEditor = () => {
alert("打开回复框");
// this.setState ({
// visible: true
// })
this.handleEditorVsiible(true);
}
renderFooter = () => {
return [
<Button key="cancel" style={{ float: 'left' }} onClick={() => handleEditorVsiible(false)} >
取消
</Button>,
<Button key="submit" type="primary" onClick={() => this.add()}>
完成
</Button>,
];
}
render() {
const { editorState, visible } = this.state
const { form } = this.props;
const extendControls = [
{
key: 'custom-button',
type: 'button',
text: '按钮',
onClick: this.insertHello
},
]
return (
<React.Fragment>
<Button key="open-editor" onClick={this.openEditor}>打开对话框</Button>
<Modal
width={840}
height={840}
bodyStyle={{ padding: '32px 40px 48px' }}
destroyOnClose
title="回复"
visible={visible}
footer={this.renderFooter()}
onCancel={() => this.handleEditorChange(false)}
afterClose={() => this.handleEditorChange()}
>
<FormItem key="smtpHost" {...this.formLayout} label="邮件服务器">
{form.getFieldDecorator('smtpHost', {
})(<Input placeholder="请输入" />)}
</FormItem>,
<FormItem key="content" {...this.formLayout} label="回复内容">
<BraftEditor
// ???
value={editorState}
extendControls={extendControls}
onChange={this.handleEditorChange}
onSave={this.submitContent}
/>
</FormItem>
</Modal>
</React.Fragment>
)
}
}
export default EditorDemo
如果想了解BraftEditor的更多细节,请访问官网