问题描述
我目前正在进行一个“论坛型”项目。类似于在 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")
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)