我在使用drafjs插件(即编辑器)时遇到了问题,当我在编辑器中键入内容时,它会跳到文本的开头。我已经找到了How to stop DraftJS cursor jumping to beginning of text?这个解决方案,但是它与我的代码有点不同,此外,我还使用React Hooks的新功能制作了该组件。拜托,您能帮我解决这个问题吗?
import {
EditorState, ContentState, convertToRaw,
} from 'draft-js'
import { Editor } from 'react-draft-wysiwyg'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import draftToHtml from 'draftjs-to-html'
import htmlToDraft from 'html-to-draftjs'
export default ({ value, onChange }) => {
const [editorState, setEditorState] = useState(EditorState.createEmpty())
useEffect(() => {
setEditorState(
EditorState.push(
editorState,
ContentState.createFromBlockArray(
htmlToDraft(value || ''),
),
),
)
}, [value])
return (
<div className="rich-editor">
<Editor
editorState={editorState}
onEditorStateChange={onEditorStateChange}
toolbar={{
options: ['inline'],
inline: {
options: ['bold', 'italic', 'underline'],
},
}}
/>
</div>
)
function onEditorStateChange(es) {
setEditorState(es)
const html = draftToHtml(convertToRaw(es.getCurrentContent()))
if (value !== html) {
onChange({ target: { name: 'text', value: html } })
}
}
}
答案 0 :(得分:0)
好吧,我有点弄清楚自己。但是,这不是最佳解决方案。基本上,我将更新后的文本转换为HTML类型,然后将值与转换后的darft.js editorState进行比较。不久,这是我的代码,如果将来对任何人有帮助的话
import React, { useEffect, useState } from 'react'
import {
EditorState, ContentState, convertToRaw,
} from 'draft-js'
import { Editor } from 'react-draft-wysiwyg'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import draftToHtml from 'draftjs-to-html'
import htmlToDraft from 'html-to-draftjs'
export default ({ value, onChange }) => {
const [editorState, setEditorState] = useState(EditorState.createEmpty())
useEffect(() => {
if (toHtml(editorState) === value) return //added
setEditorState(
EditorState.push(
editorState,
ContentState.createFromBlockArray(
htmlToDraft(value || ''),
),
),
)
}, [value])
return (
<div className="rich-editor">
<Editor
editorState={editorState}
onEditorStateChange={onEditorStateChange}
toolbar={{
options: ['inline'],
inline: {
options: ['bold', 'italic', 'underline'],
},
}}
/>
</div>
)
function onEditorStateChange(es) {
setEditorState(es)
const html = toHtml(es) //added
if (value !== html) {
onChange({ target: { name: 'text', value: html } })
}
}
function toHtml(es) {
return draftToHtml(convertToRaw(es.getCurrentContent())) // added
}
}