我被困在这一天了。阅读了多个答案,但没有找到任何答案。
我的任务很简单,我有一个用户可以回答问题的页面。
-
页面将有两个编辑器打开(默认情况下)。(在react-quill GitHub讨论中发现)。
-
将有一个"添加步骤"按钮,当然,在下面添加另一个羽毛笔编辑器,用户可以添加尽可能多的步骤,因为他/她喜欢。
-
编辑器旁边将有一个"删除"按钮来删除编辑器,除了前两个编辑器。
现在,我想在我的DB中单独存储上述步骤,但是编辑器上的onClick
没有e.target
,相反,它只是给出了HTML值。因此,我如何在onClick上添加编辑器并将值与多个编辑器分开呢?
对解决方案的任何方向或提示将不胜感激。谢谢。
可以使用Array of Objects.
这可以通过两个独立的组件来实现,
- 一个用于RichText Editor,
- 一个有状态(对象数组)的主组件
在下面的代码中,我使用react-quill库作为文本编辑器,使用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>
);
}