我已经尝试过,在这里我添加了两个按钮,当用户单击状态中的值存储时,该状态被传递给编辑器,作为道具复制。然后我试图将值转换为 html 代码,然后连接复制道具,然后再次转换为 html 到草稿格式,然后更新状态,但我无法修复。
Codesandbox 链接:代码
当用户单击按钮时我想要什么,它应该在编辑器中附加文本值。
能够根据单击添加文本,但现在的问题是根据光标位置附加文本,目前它添加到末尾,我想添加到用户指向光标的位置,然后单击应该添加到那里的按钮
最新代码:更新了添加文本功能的代码
父组件
import EditorWrapper from "./Editor";
export default function App() {
const [copy, setCopy] = useState("");
return (
<>
<div className="App">
<div className="d-flex">
<button
onClick={() => setCopy("Welcome")}
className="btn btn-primary me-2"
>
Welcome
</button>
<button
onClick={() => setCopy("Thank you")}
className="btn btn-primary"
>
Thank you
</button>
</div>
<EditorWrapper copy={copy} />
</div>
</>
编辑器组件
import "./styles.css";
import React, { useState, useEffect } from "react";
import { Editor } from "react-draft-wysiwyg";
import { EditorState, ContentState, convertToRaw } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import htmlToDraft from "html-to-draftjs";
import draftToHtml from "draftjs-to-html";
export default function EditorWrapper({ copy }) {
const initialState = () => EditorState.createEmpty();
const [editorState, setEditorState] = useState(initialState);
const onChange = async (value) => {
// const data = draftToHtml(convertToRaw(value.getCurrentContent()));
// console.log(data.concat(`<p>${copy}</p>`));
// const contentBlock = htmlToDraft(data);
// const contentState = ContentState.createFromBlockArray(
// contentBlock?.contentBlocks
// );
// const updateState = EditorState.createWithContent(contentState);
setEditorState(value);
};
return (
<Editor
editorState={editorState}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
onEditorStateChange={(value) => onChange(value)}
stripPastedStyles
ariaLabel="draftEditor"
/>
);
}