React Formik 中的动态输入字段

Dynamic Input field in React Formik

我有一个表单,其中有一个输入和一个日期选择器,这两个将来自 API 端点。

如何保存输入值?

const [startDate, setStartDate] = useState(new Date());

const apiData = [
    {id: "abc", name: "form 1"},
    {id: "abd", name: "form 2"},
    {id: "abz", name: "form 3"},
    {id: "asd", name: "form 4"},
    {id: "acd", name: "form 5"},
];
...   
{apiData?.map((item) => {
    return (
       <input // accept only number
           type="text"
           name={item.id}
           placeholder="Fee"
           className="fee-form"
       />
       <DatePicker
           selected={startDate}
           onChange={(date) => setStartDate(date)}
           className="date-pic-brand-form"
       />
    );
})}

以上代码将生成 5 个表单字段。

如何保存每个输入字段的数据?

谢谢。

像这样:

const [data, setData] = useState([]);

const apiData = [
    {id: "abc", name: "form 1"},
    {id: "abd", name: "form 2"},
    {id: "abz", name: "form 3"},
    {id: "asd", name: "form 4"},
    {id: "acd", name: "form 5"},
];
...   

useEffect(() => {
    const newData = [];
    apiData.forEach(() => {
        newData.push({});
    });
    setData(newData);
}, [apiData]);

const handleChange = (field, value, index) => {
    setData(prevState => {
        const nextState = [...prevState];
        nextState[index][field] = value;
        return nextState;
    })
}
{
    apiData?.map((item, index) => {
    return (
    <input // accept only number
        type="text"
        name={item.id}
        placeholder="Fee"
        className="fee-form"
        onChange={e => handleChange('id', e.target.value, index)}
    />
    <DatePicker
        selected={startDate}
        onChange={date => handleChange('date', date, index)}
        className="date-pic-brand-form"
    />
    );
})}

最后,所有数据都在 data 状态。