如何在 React 中根据数据创建对象?

根据下面的代码,如何在 React 状态(对于函数组件)中创建对象模型?


<div class="form-row">

    <label>Input 1</label>

    <input id="1" />

</div>


<div class="form-row">

    <label>Input 2</label>

    <input id="2" />

</div>


<div class="form-row">

    <label>Input 3</label>

    <input id="3" />

</div>


<div class="form-row">

    <label>Input 4</label>

    <input id="4" />

</div>

const dataToPost = [

        ...document.querySelectorAll("div.form-row"),

    ].map((f) => {

        let obj = {};

        f.querySelectorAll("input").forEach(

            (item) => (

                (obj["id"] = item.id), (obj["value"] = item.value || "")

            )

        );

        return obj;

    });

这将输出我想要的结果...


"dataToPost": [

    {

        "id": "1",

        "value": "input one value"

    },

    {

        "id": "2",

        "value": "input two value"

    },

    {

        "id": "3",

        "value": "input three value"

    },

    {

        "id": "4",

        "value": "input four value"

    }

]


那么,是否可以对每个输入使用 on change 事件来更新其状态对象,因为它需要是一个函数组件?


浮云间
浏览 151回答 1
1回答

子衿沉夜

您需要创建自定义挂钩以将表单的状态保持在所需的格式,并在事件中更新表单状态onChange请按照以下步骤操作:转换<div class="form-row">&nbsp; &nbsp; <label>Input 1</label>&nbsp; &nbsp; <input id="1" /></div>将表示单个输入元素及其标签的组件中。创建一个将保留窗体状态的自定义挂钩import { useState, useCallback } from "react";function useForm() {&nbsp; const [data, setData] = useState([&nbsp; &nbsp; { id: 1, value: "" },&nbsp; &nbsp; { id: 2, value: "" },&nbsp; &nbsp; { id: 3, value: "" },&nbsp; &nbsp; { id: 4, value: "" }&nbsp; ]);&nbsp; const updateForm = useCallback(&nbsp; &nbsp; ({ target }) => {&nbsp; &nbsp; &nbsp; &nbsp; const arr = [...data];&nbsp; &nbsp; &nbsp; &nbsp; const obj = arr.find(o => o.id === Number(target.name));&nbsp; &nbsp; &nbsp; &nbsp; obj.value = target.value;&nbsp; &nbsp; &nbsp; &nbsp; setData(arr);&nbsp; &nbsp; },&nbsp; &nbsp; []&nbsp; );&nbsp; return [data, updateForm];}export default useForm;创建将呈现所有组件的组件。此组件将使用在步骤 2 中创建的挂钩。在此组件中,我们将循环访问表单状态并呈现各个组件,并将适当的 props 传递给元素,并且还会传递事件处理程序,该处理程序将在任何输入更改时更新表单状态。FormInputFormuseFormInputInputonChangeimport React from "react";import useForm from "./useForm";import Input from './Input';function Form() {&nbsp; &nbsp;const [data, setData] = useForm();&nbsp; &nbsp;return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; data.map((input, idx) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<Input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key={idx}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type="text"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={input.value}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label={`Input ${++idx}`}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name={input.id}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setValue={setData}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;/>&nbsp; &nbsp; &nbsp; &nbsp; ))&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; </>&nbsp; );}export default Form;这是上述步骤的工作演示。附注钩子,并已用于优化。这可以防止在任何组件上触发事件时对所有组件进行不必要的重新呈现useCallbackReact.memoInputonChangeInput
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript