[英]access to nested objects and arrays React
const [data, setData] = useState({
questionText: "",
answerOptions: [
{ answerText: "", isCorrect: "" },
{ answerText: "", isCorrect: "" },
{ answerText: "", isCorrect: "" },
{ answerText: "", isCorrect: "" },
],
});
如何在输入标签的 onChange 中更改 answerText 或 isCorrect 的值?
<input
type="text"
onChange={(event) =>
setData({ ...data, answerText: event.target.value })
}
/>
由于您的answerOptions
是一个数组,因此您也需要对数组使用相同的扩展运算符。
data = { questionText: "", answerOptions: [ { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, ], } console.log({...data, answerOptions: [...data.answerOptions, {answerText: 'something', isCorrect: "some value"}]})
上面的代码将向现有数组添加一个新的 object。 如果你想编辑现有的 object,我建议使用唯一标识符找出 object 并使用.map()
更新它
data = { questionText: "", answerOptions: [ { answerText: "", isCorrect: "", id: 1 }, { answerText: "", isCorrect: "", id: 2 }, { answerText: "", isCorrect: "", id: 3 }, { answerText: "", isCorrect: "", id: 4 }, ], } console.log({...data, answerOptions: [...data.answerOptions.map(element => element.id == 2? {...element, answerText: 'updated text' }: element)] })
您可以在反应应用程序中尝试相同的逻辑并更新您的 state 变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.