您可以使用Array of Objects获得单独的值。
它可以通过两个独立的组件来完成,
- 一种用于富文本编辑器,
- 具有状态的主要组件(对象数组)
我在下面的代码中使用了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;
应用程序.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>
);
}