You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Hooks中如何实现点击按钮新增多个CKEditor实例?

问题原因

你当前的代码用布尔类型的clicked状态控制单个编辑器的显隐,且只有一个全局text变量存储内容,自然只能实现切换显隐的效果,无法新增多个独立的编辑器实例。

解决思路

用数组存储所有编辑器的独立内容,每次点击按钮就往数组新增一个空初始内容,遍历数组渲染对应数量的CKEditor实例,每个实例独立绑定对应下标的内容。

修改后完整代码

import React, { useState } from "react";
import { CKEditor } from "@ckeditor/ckeditor5-react";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";

const Followups = () => {
  // 用数组存储每个编辑器的内容,每个元素对应一个编辑器的内容
  const [editorList, setEditorList] = useState([]);

  const addEditor = () => {
    // 点击新增一个空内容的编辑器
    setEditorList(prevList => [...prevList, ""]);
  };

  // 修改对应下标编辑器的内容
  const handleEditorChange = (index, newContent) => {
    setEditorList(prevList => {
      const newList = [...prevList];
      newList[index] = newContent;
      return newList;
    });
  };

  return (
    <>
      {/* 遍历数组渲染多个CKEditor实例 */}
      {editorList.map((content, index) => (
        <CKEditor
          key={index}
          editor={ClassicEditor}
          data={content}
          onChange={(event, editor) => {
            const data = editor.getData();
            handleEditorChange(index, data);
          }}
          config={{
            toolbar: [
              "heading",
              "|",
              "bold",
              "italic",
              "blockQuote",
              "numberedList",
              "bulletedList",
              "|",
              "undo",
              "redo",
            ],
          }}
        />
      ))}
      
      <button onClick={addEditor}>Follow-ups</button>
    </>
  );
};
export default Followups;

关键调整说明

  • 把原来的布尔类型clicked状态替换为数组类型editorList,数组长度就是编辑器的数量,每个元素存储对应编辑器的内容
  • 点击按钮不再切换布尔值,而是往数组末尾追加一个空字符串,触发新增一个编辑器
  • 遍历数组渲染CKEditor,每个实例通过下标绑定对应内容,修改时只会更新对应下标的内容,多个编辑器之间互不影响

内容的提问来源于stack exchange,提问作者Abdul Sammad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 22:24:02