在寫react時需要用到富文本編輯器,找了很多後最後選擇了braft-editor富文本編輯器
- 美觀易用的react富文本編輯器
- 可結合antd使用
- 本質是封裝的
draft-js
- 提供多媒體的功能(圖片、音頻、視頻)
這裏我只介紹常見的一些功能和問題,詳情請參考官網
基本使用
通過value
和onChange
對editorState
組件進行雙向綁定,注意value的值的類型必須是editorState對象
(這一點類似於Ant Design中的日期選擇器組件,它使用moment對象作爲數據格式)
import BraftEditor from 'braft-editor'
...
state = {
editorState: BraftEditor.createEditorState(null)
}
...
handleChange = (editorState) => {
this.setState({ editorState })
}
...
<BraftEditor
value={this.state.editorState}
onChange={this.handleChange}
/>
判斷富文本編輯的內容是否爲空
this.state.editorState.isEmpty()
清空富文本編輯器的內容
this.setState({
editorState: ContentUtils.clear(this.state.editorState)
})
}
我剛開始的時候直接用editorState:BraftEditor.createEditorState(null)
來清空富文本編輯器的內容,但是清空後發現光標跳動,最後用了上面clear方法清空才解決問題。
多媒體上傳
- 獲取上傳的文件(param.file)
- 上傳到服務器(這裏可用任何一個ajax作爲通信工具,我使用的是fetch)
- 獲取上傳結果,根據結果調用param的方法
myUploadFn = async (param) => {
const formData = new FormData();
formData.append('file', param.file);
const res = await fetch(`${process.env.REACT_APP_BASE_URL}/upload`, {
method: 'POST',
headers: {
Authorization: `Bearer ${isAuthenticated()}`,
},
body: formData
}).then(response => response.json())
if (res.status === 0) {
param.success(res.data) //success需要一個有url屬性的對象{url:'...'}
} else {
param.error({
msg: '上傳錯誤'
})
}
}
定製鍵盤命令
BraftEditor
組件其實是封裝的DraftJS,BraftEditor
組件沒有提供鍵盤的回車事件,我們可以用DraftJS的屬性去做鍵盤事件
...
//定製鍵盤命令
handleKeyCommand = (command) => {
//如果是回車命名就處理
if (command === 'split-block') {
//回車事件的處理函數
this.test()
return 'handled';
}
return 'not-handled';
}
<BraftEditor
//直接傳給DraftJS的Editor組件的屬性
draftProps={{
handleKeyCommand: this.handleKeyCommand
}}
/>
當富文本編輯器按下鍵盤命令時,會觸發handleKeyCommand,將此時觸發的命令作爲參數傳遞到處理函數中。
回車命令、退格命令、保存命令(ctrl+s)分別對應split-block、backspace、braft-save。當處理函數handleKeyCommand返回’handled’,則認爲該命令已處理。如果它返回’not-handled’,執行默認命令