我有一个 React 应用程序,它有一个 TinyMCE 实例,在更改编辑器的特定部分后,我想将它们保存在后端,只有那些已经更改的部分。有可能实现这样的目标吗?在 vanillajs 和 html 中,您会有不同的
divs
和 ids
,您可以获取它们的参考并更改相应的部分。但在 React 中就不一样了。
我尝试的是通过使用将这些部分作为字典的状态变量将来自后端的文本呈现到编辑器中,但现在我只想更改一个部分来更改相应的值。我想派生的是更新服务器的部分名称(以及状态变量中的相应键值对)。在示例中,我提供的每个部分的 html 内容很小,但在真实的应用程序中它可能很大。该模型是一个字典,它以部分名称作为键,以具有 id 和 html 值的对象作为值,如下所示:
{
header: { section_id: 2, value: "<h1> This is the header </h1>"},
body: { section_id: 1, value: "<p>Body content</p>" }
...
}
function MyComponent() {
// here is the state var that I am taking from the backend
// and want to update it according to user changes
const [value, setValue] = useState({
header: { section_id: 2, value: "<h1>This is the header</h1>" },
body: { section_id: 1, value: "<p>Body</p>" }
});
const editorValue = Object.values(value)
.map((v) => v.value)
.join("<br/>");
return (
<Editor
value={editorValue}
onEditorChange={(newValue, editor) => {
// here I would like to get the section part which I am updating somehow
setValue(newValue);
}}
/>
);
}
有没有办法根据我的尝试或我可以遵循的另一种方法以某种方式获取部分参考以实现相同的目标?
所以我最后做了以下事情:
我使用字典来遍历我拥有的值,并创建与我在字典中拥有的值一样多的编辑器。通过这种方式,我可以传递我正在动态更改的部分的密钥,并且我知道我正在更新哪个部分,因此我可以将更改后的文本发送到后端以单独保存。
const [editorValue, setEditorValue] = useState({
header: { section_id: 2, value: "<h1>This is the header</h1>" },
body: { section_id: 1, value: "<p>This is the body</p>" }
});
const handleEditorChange = (value, editor, key) => {
setEditorValue((prevState) => ({
...prevState,
[key]: { ...prevState[key], value }
}));
};
return Object.entries(editorValue).map(([key, value]) => (
<Editor
inline
menubar={false}
value={value.value}
onEditorChange={(value, editor) => handleEditorChange(value, editor, key)}
/>
));
我还更新了demo以包含我的解决方案,以防将来有人遇到同样的问题。