由於自己使用的是純函數,所以這里不多說,直接開始
在form表單中使用,首先去掉form.item的name屬性,在利用useState去賦值
<ProForm.Item
label="文章內容"
>
<BraftEditor
value={content}
controls={controls}
onChange={(editorState) => { setContent(editorState) }}
extendControls={extendControlsContent}
></BraftEditor>
</ProForm.Item>
在這里自己使用的是ProComponents
其實和ant design相同只不過再次封裝了一次,(不過不是特別好用)
給content進行初始化賦值
const [content, setContent] = useState(BraftEditor.createEditorState(null))
然后就是上傳圖片時利用的ant-design upload組件
const extendControlsContent: any = [
{
key: 'antd-uploader',
type: 'component',
component: (
<Upload
accept="*"
showUploadList={false}
onChange={handleImageContentChange}
action='http://127.0.0.1:9097/upload/image'
>
<button type="button" className="control-item button upload-button" data-title="插入圖片">上傳圖片</button>
</Upload>
)
}
]
最重要的就是onChange事件
const handleImageContentChange = (info: any) => {
if (info?.file?.response?.message == "success") {
setContent(ContentUtils.insertMedias(content, [{
type: 'IMAGE',
url: info?.file?.response?.url
}]))
}
}
特別是在上一個onChange事件中,set傳入的值注意一下,
提交表單的時候在進行處理,輸出html格式
val.content = content.toHTML()
在修改表單的時候去賦值
useEffect(() => {
if (values?.id) {
setContent(BraftEditor.createEditorState(values?.content))
}
}, [])
特別注意的時候就是,文字和圖片結合,文字在前的時候會報 getSelection 錯誤,這也是為了記錄一下自己解決這個問題的步驟