braft-utils
braft-utils copied to clipboard
antd-form+braft-editor+antd-upload一起使用,图片上传成功后无法正确在编辑器内显示
import 'braft-editor/dist/index.css'
import React, { PureComponent } from 'react'
import BraftEditor from 'braft-editor'
import { ContentUtils } from 'braft-utils'
import { ImageUtils } from 'braft-finder'
import { Divider, Button, Form, Input, Select, Spin, Upload, Icon, message, InputNumber } from 'antd'
const FormItem = Form.Item
@Form.create()
class Operate extends PureComponent {
state = {
controls: ['bold', 'italic', 'underline', 'text-color', 'fullscreen'],
editorState: BraftEditor.createEditorState(null),
}
handleChange = (editorState) => {
this.setState({ editorState })
}
uploadHandler = (param) => {
if (!param.file) {
return false
}
const { editorState } = this.state
const url = 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
this.setState({
editorState: ContentUtils.insertMedias(editorState, [{
type: 'IMAGE',
url: url,
}]),
})
}
render() {
const { getFieldDecorator } = this.props.form
const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 17 } }
const extendControls = [
{
key: 'antd-uploader',
type: 'component',
component: (
<Upload accept="image/*" showUploadList={false} customRequest={this.uploadHandler}>
<button type="button" className="control-item button upload-button" data-title="插入图片">
<Icon type="picture" theme="filled"/>
</button>
</Upload>
),
},
]
const { controls, editorState } = this.state
return (
<div style={{ width: '720px' }}>
<Form onSubmit={this.handleSubmit}>
<FormItem {...formItemLayout} label="操作说明">
{getFieldDecorator('content', {
initialValue: editorState,
validateTrigger: 'onBlur',
rules: [{
required: true,
validator: (_, value, callback) => {if (value.isEmpty()) {callback('请输入操作说明')} else {callback()}}, }],
})(
<BraftEditor
style={{ border: '1px solid #e5e5e5', borderRadius: '3px' }}
onChange={this.handleChange}
onFullscreen={this.handleFullscreen}
controls={controls}
extendControls={extendControls}
/>,
)}
</FormItem>
</Form>
</div>
)
}
}
export default Operate
npm的版本,用这段代码,未知原因不能成功setValue
需要重新获得instance之后,然后instance.setValue(state)才可以
class DemoBraftEditor extends React.Component{
state:ComponentState = {
editorState: BraftEditor.createEditorState(null),
}
editorInstance:BraftEditor|undefined
...
uploadHandler = (param:UploadFile) => {
this.setState((prevState: ComponentState) => ({
editorState: ContentUtils.insertMedias(prevState.editorState, [
{
type: 'IMAGE',
url: URL.createObjectURL(param.file),
},
]),
}));
this.editorInstance?.setValue(this.state.editorState);
}
render(){
...
return(
...
<BraftEditor
id="demo-editor-with-emoticon"
// eslint-disable-next-line no-return-assign
ref={instance => (this.editorInstance = instance)}
className={styles.myEditor}
placeholder="请输入正文内容"
value={this.state.editorState}
onChange={this.handleChange}
customRequest={this.uploadHandler}
/>
...
)
}
}
手动setValue应该就可以了