[英]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.