Render/Add 在 React 中单击按钮时的羽毛笔编辑器

Render/Add quill editor on click of a button in react

我现在被困在这个问题上一天了。 已阅读多个答案,但找不到任何内容。

我的任务很简单,我有一个用户可以回答问题的页面。

现在,我也想将上述步骤单独存储在我的数据库中,但是编辑器上的 onClick 没有 e.target,而是只给出 HTML 价值。因此,如何添加编辑器 onClick 并将值与多个编辑器分开?

对于解决方案的任何方向或提示,我们将不胜感激。谢谢

您可以通过使用对象数组获得单独的值。

可以通过两个独立的组件来完成,

  1. 一个用于富文本编辑器,
  2. 具有状态(对象数组)的主要组件

我在以下代码中使用了 react-quill library for text editor and react-bootstrap 样式。您可以选择替换其中一个或两个

创建两个组件:

 - App.js // Main component
 - ReactQuill.js // Editor component 

ReactQuill.js

    import React from "react";
    import ReactQuill from "react-quill";
    
    import "react-quill/dist/quill.snow.css";
    
    class ReactQuillEditor extends React.Component {
      render() {
        const { response, handleChange } = this.props;
        return (
          <ReactQuill
            style={{ marginTop: "4px" }}
            value={response}
            onChange={handleChange}
          />
        );
      }
    }
    
    export default ReactQuillEditor;

App.js

import { useState } from "react";
import { Button } from "react-bootstrap";

// Editor Component
import Editor from "./components/ReactQuill";

export default function App() {
  const [steps, setStep] = useState([
    {
      step: 1,
      response: ""
    },
    {
      step: 2,
      response: ""
    }
  ]); // For Default Two Inputs

  const handleChange = (value, index) => {

    // Updates, Remove and Replaces an object at index n
    const steptoReplace = steps[index];
    steptoReplace.response = value;

    steps.splice(index, 1);
    steps.splice(index, 0, steptoReplace);

    setStep(steps);
  };

 // Adds an empty entry
  const addStep = () => {
    setStep([
      ...steps,
      {
        step: steps.length + 1,
        response: ""
      }
    ]);
  };

  const reduceStep = () => {
    // To have Two text editor always
    if (steps.length > 2) {
      steps.pop();
      setStep([...steps]);
    }
  };

  const submit = () => {
    // You will have an Array of Objects of all steps
    console.log("steps", steps);
  };

  return (
    <div className="container">
      <h1>Multiple React Quill</h1>
      <div className="mt-4">
        {steps.map((step, index) => (
          <div key={index}>
            Step {index + 1}
            <Editor
              response={step.response}
              handleChange={(value) => handleChange(value, index)}
            />
          </div>
        ))}

        <div className="d-flex mt-4  justify-content-between">
          <Button onClick={addStep}>Add Step </Button>
          <Button onClick={reduceStep}>Remove Step</Button>
        </div>

        <Button className="mt-4" onClick={() => submit()}>
          Submit
        </Button>
      </div>
    </div>
  );
}