我目前正在进行一个“论坛型”项目。类似于在 StackOverflow 上发布帖子时弹出的工具栏 + 任何格式的预览,我想在我的项目中实现相同的效果。
过去两天我一直在用 Draft.js 来加重自己的负担,并最终设法让富编辑器工作。这意味着我可以格式化文本等。问题是 - 虽然我可以将文本保存到我的数据库并在浏览器中显示它 - 我只是不知道我应该如何将富文本从客户端传输到我的数据库和然后显示在页面上。
这是我用来支持富文本编辑器的代码:
import React, { useState, useEffect, useContext } from "react"
import { EditorState } from "draft-js"
import { Editor } from "react-draft-wysiwyg"
import { convertToHTML } from "draft-convert"
import StateContext from "../StateContext"
import DispatchContext from "../DispatchContext"
import Axios from "axios"
import { withRouter } from "react-router-dom"
import DOMPurify from "dompurify"
import { PreviewModal } from "./previewModal"
function TextEditor(props) {
const [title, setTitle] = useState()
const appDispatch = useContext(DispatchContext)
const appState = useContext(StateContext)
const [editorState, setEditorState] = useState(() => EditorState.createEmpty())
const [convertedContent, setConvertedContent] = useState(null)
const handleEditorChange = state => {
setEditorState(state)
convertContentToHTML()
}
const convertContentToHTML = () => {
let currentContentAsHTML = convertToHTML(editorState.getCurrentContent())
setConvertedContent(currentContentAsHTML)
}
const createMarkup = html => {
return {
__html: DOMPurify.sanitize(html)
}
}
async function handleSubmit(e) {
e.preventDefault()
try {
const response = await Axios.post("/create-post", { title, body, token: appState.user.token })
//Redirect
appDispatch({ type: "flashMessage", value: "Congrats you created a new post!" })
props.history.push(`/post/${response.data}`)
console.log("new post")
} catch (e) {
console.log("problem")
}
}
const body = editorState.getCurrentContent().getPlainText("\u0001")
return (
<div className="form-group">
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="post-title" className="text-muted mb-1">
<small>Title</small>
</label>
<input onChange={e => setTitle(e.target.value)} autoFocus name="title" id="post-title" className="form-control form-control-lg form-control-title" type="text" placeholder="" autoComplete="off" />
</div>
<div className="form-group">
<label htmlFor="post-body" className="text-muted mb-1 d-block">
<small>Content</small>
</label>
<div className="App">
<Editor editorState={editorState} onEditorStateChange={handleEditorChange} name="body" id="post-body" className="body-content tall-textarea form-control" type="text" />
</div>
</div>
<button className="btn btn-primary">Save New Post</button>
</form>
</div>
)
}
export default withRouter(TextEditor)
这段代码基本上允许我在保存时实际显示文本:
const body = editorState.getCurrentContent().getPlainText("\u0001")