简体   繁体   English

访问嵌套对象和 arrays React

[英]access to nested objects and arrays React

const [data, setData] = useState({
    questionText: "",
    answerOptions: [
      { answerText: "", isCorrect: "" },
      { answerText: "", isCorrect: "" },
      { answerText: "", isCorrect: "" },
      { answerText: "", isCorrect: "" },
    ],
  });

How can I change the value of answerText or isCorrect in onChange of input tag?如何在输入标签的 onChange 中更改 answerText 或 isCorrect 的值?

<input
        type="text"
       
        onChange={(event) =>
          setData({ ...data, answerText: event.target.value })
        }
      />

Since your answerOptions is an array so you need to follow the same spread operator for the array also.由于您的answerOptions是一个数组,因此您也需要对数组使用相同的扩展运算符。

 data = { questionText: "", answerOptions: [ { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, { answerText: "", isCorrect: "" }, ], } console.log({...data, answerOptions: [...data.answerOptions, {answerText: 'something', isCorrect: "some value"}]})

The above code will add a new object to an existing array.上面的代码将向现有数组添加一个新的 object。 If you want to edit the existing object, I would suggest using a unique identifier to find out the object and update it using .map()如果你想编辑现有的 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)] })

You can try the same logic in you react app and update your state variable您可以在反应应用程序中尝试相同的逻辑并更新您的 state 变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM