在 React Hooks 项目中应用 Draft Wysiwyg
Applying Draft Wysiwyg in React Hooks Project
我尝试将 react draft wysiwyg 集成到我的 React Hooks 项目中。
我这样初始化描述:
var editorState = EditorState.createEmpty()
const [description, setDescription] = React.useState(editorState);
...我这样应用编辑器:
<Editor
editorState={description}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
onEditorStateChange={setEditorState}
/>
这是 setEditorState:
const setEditorState = (editorState) => {
console.log('editorState', editorState)
setDescription(editorState)
}
当我在编辑器上输入时,描述 不是我输入的内容,而是像这样的对象:
_immutable: {allowUndo: true,…}
更新 1
我还发现当前内容就是我输入的内容。像这样访问数据是正确的方法吗?
_immutable.currentContent.text
更新 2
我也试过像这样直接设置编辑器状态,但没有帮助:
onEditorStateChange={setDescription}
我错过了什么?
谢谢
好的,我通过转换 to/from html 解决了这个问题。
这足以将编辑器状态转换为 html。
import {stateToHTML} from 'draft-js-export-html';
....
let html = stateToHTML(editorState.getCurrentContent());
并且当我将 html 转换回编辑器状态时,我像在 documentation 中一样应用。
const html = props.content;
const contentBlock = htmlToDraft(html);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
editorStateInitial = EditorState.createWithContent(contentState);
}
const [editorState, setEditorState] = React.useState(editorStateInitial);
这个转换圈解决了问题。
我尝试将 react draft wysiwyg 集成到我的 React Hooks 项目中。
我这样初始化描述:
var editorState = EditorState.createEmpty()
const [description, setDescription] = React.useState(editorState);
...我这样应用编辑器:
<Editor
editorState={description}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
onEditorStateChange={setEditorState}
/>
这是 setEditorState:
const setEditorState = (editorState) => {
console.log('editorState', editorState)
setDescription(editorState)
}
当我在编辑器上输入时,描述 不是我输入的内容,而是像这样的对象:
_immutable: {allowUndo: true,…}
更新 1 我还发现当前内容就是我输入的内容。像这样访问数据是正确的方法吗?
_immutable.currentContent.text
更新 2 我也试过像这样直接设置编辑器状态,但没有帮助:
onEditorStateChange={setDescription}
我错过了什么? 谢谢
好的,我通过转换 to/from html 解决了这个问题。
这足以将编辑器状态转换为 html。
import {stateToHTML} from 'draft-js-export-html';
....
let html = stateToHTML(editorState.getCurrentContent());
并且当我将 html 转换回编辑器状态时,我像在 documentation 中一样应用。
const html = props.content;
const contentBlock = htmlToDraft(html);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
editorStateInitial = EditorState.createWithContent(contentState);
}
const [editorState, setEditorState] = React.useState(editorStateInitial);
这个转换圈解决了问题。