我在React页面上使用EditorJS,以允许人们在基于块的编辑器中编写代码。但是,我也想构建部分,其中用户可以有多个部分,每个部分可以支持一个EditorJS组件
当我添加一个新的区段时,我遇到了一个问题,我想为这个新区段呈现一个空的EditorJS组件(并保留来自旧区段和EditorJS实例的数据)。它不是空实例,而是从旧实例复制信息,并将其分配给新的Section。类型定义如下
types.d.ts
interface User {
...
sections: Section[],
}
interface Section {
id: string,
name: string,
content: ContentBlock,
}
interface ContentBlock {
id: string,
threads: Thread[],
content: OutputData, //this is the EditorJS saved data
}我想知道EditorJS是否保持了某种全局状态,它正在应用于我的应用程序中的每个实例。有没有人有使用多个editorJS实例的经验?
作为参考,我有两个组件:Page.tsx和Section.tsx。相关代码如下
//Page.tsx
const Page: React.FC = () => {
const [allSections, setAllSections] = useState<Section[]>([]);
const [currSectionID, setCurrSectionID] = useState("");
const addNewSection = (type: string) => {
const newID = uuidv4();
const newSection: Section = {
id: newID,
name: "",
content: emptyContentBlock,
};
setAllSections(arr => [...arr, newSection]);
setCurrSectionID(newID);
};
const updateContentForSection = (contentBlock: ContentBlock, sectionID: string) => {
const newSectionArray = [...allSections];
newSectionArray.forEach((section: Section) => {
if (section.id === sectionID) {
section.content = contentBlock
}
});
setAllSections(newSectionArray);
};
return (
<Section
sectionID={currSectionID}
sections={allSections}
pageActions = {{
addNewSection: addNewSection,
updateContentForSection: updateContentForSection,
}}
/>
)
}//Section.tsx
const Section: React.FC<SectionInput> = (props) => {
const currSection = props.sections.filter(section => section.id === props.sectionID)[0];
const blocks = currSection? currSection.content.content : [];
const [editorInstance, setEditorInstance] = useState<EditorJS>();
const saveEditorData = async() => {
if (editorInstance) {
const savedData = await editorInstance.save();
console.log(`saving data to section ${props.sectionID}`, savedData);
props.pageActions.updateContentForSection({content: savedData, id: props.sectionID, threads: threads}, props.sectionID);
}
}
}
return (
<div>
<button
className={`absolute top-0 right-12 mt-2 focus:outline-none`}
onClick={() => {
props.pageActions.addNewSection()
}}
>
Add Section
</button>
<EditorJs
key="0"
holder="custom"
data={blocks}
autofocus={true}
instanceRef={(instance: EditorJS) => {
setEditorInstance(instance)
}}
onChange={saveEditorData}
tools={EDITOR_JS_TOOLS}
>
<div
id="custom"
>
</div>
</EditorJs>
</div>
)发布于 2021-01-23 00:05:07
因此,根据这个github thread,答案实际上很简单。对于要放在DOM中的每个编辑器,请为每个editorJS ID使用唯一的ID。然后,代码变成如下所示
<EditorJs
key={`${sectionID}`}
holder={`custom${sectionID}`}
data={blocks}
autofocus={true}
instanceRef={(instance: EditorJS) => {
setEditorInstance(instance)
}}
onChange={saveEditorData}
tools={EDITOR_JS_TOOLS}
>
<div
id={`custom${sectionID}`}
>
</div>
</EditorJs>https://stackoverflow.com/questions/65838833
复制相似问题