【发布时间】:2020-12-16 09:39:54
【问题描述】:
我是 React 新手,到目前为止我只学会了使用 hooks 编写代码。
我做了动态输入,用户可以根据需要添加任意数量的输入。 我想允许用户重新排列输入的顺序。
我尝试了一些代码(见下文),但它以警告告终。
警告:组件正在将受控输入更改为不受控制。
如何重新排列输入的顺序?
const Questions = ({ questionsData, setQuestionsData, title, id }) => {
console.log(questionsData);
const handleSave = async () => {
if (id) {
try {
const response = await axios.post("http://localhost:3001/update", {
id: id,
title: title,
questions: questionsData,
});
alert(response.data);
} catch (error) {
console.log(error.message);
}
} else if (!id && title !== "") {
try {
const response = await axios.post("http://localhost:3001/create", {
title: title,
questions: questionsData,
});
alert(response.data.message);
} catch (error) {
console.log(error.message);
}
} else {
alert("Le Formulaire doit avoir un titre.");
}
};
return (
<>
{questionsData.map((question, index) => {
return (
<div key={question + index} className="questions">
<div className={question.type === "texte" ? "orange" : "red"}>
<span>{question.type === "texte" ? "1" : "2"}</span>
<img src={Minus} alt="" />
<img
src={question.type === "texte" ? FileWhite : StarWhite}
alt=""
/>
</div>
<input
type="text"
placeholder="Ecrivez votre question"
value={question.title}
onChange={(event) => {
let tab = [...questionsData];
tab[index].title = event.target.value;
tab[index].index = index;
setQuestionsData(tab);
}}
></input>
<div>
<img
src={ChevronUp}
alt="move up"
onClick={() => {
let tab = [...questionsData];
let item = tab.splice(index, 1);
tab.splice(index + 1, 0, item);
setQuestionsData(tab);
}}
/>
<img src={ChevronDown} alt="move down" />
<img
src={SmallTrash}
alt="delete question"
onClick={() => {
let tab = [...questionsData];
tab.splice(index, 1);
setQuestionsData(tab);
}}
/>
</div>
</div>
);
})}
<div className="questionType">
<div
className="addText"
onClick={() => {
let tab = [...questionsData];
tab.push({ type: "texte", title: "", index: "" });
setQuestionsData(tab);
}}
>
<img src={File} alt="" />
<p>Ajouter une question "Texte"</p>
</div>
<div
className="addNote"
onClick={() => {
let tab = [...questionsData];
tab.push({ type: "note", title: "", index: "" });
setQuestionsData(tab);
}}
>
<img src={Star} alt="" />
<p>Ajouter une question "Note"</p>
</div>
</div>
<div className="save">
<button onClick={handleSave}>Sauvegarder</button>
</div>
</>
);
};
export default Questions;
【问题讨论】: