【问题标题】:Dynamic Input field in React FormikReact Formik 中的动态输入字段
【发布时间】:2022-01-12 06:08:33
【问题描述】:

我有一个表单,它有一个输入和一个日期选择器,这两个将来自 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 个表单域。

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

谢谢。

【问题讨论】:

    标签: reactjs formik


    【解决方案1】:

    类似这样的:

    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 state 中的所有数据。

    【讨论】:

    • TypeError: 无法在这一行设置未定义(设置“id”)的属性 nextState[index][field] = value;
    • codesandbox.io/s/crazy-wind-qyeeg 我已经更新了这里的代码,我想要另一种格式的输出,你能帮我吗?
    • 详细解释格式?
    • { somekey1: [ { id: "abc", fee: "234", data: "23-11-2021" }, { id: "abc", fee: "234", data : "23-11-2021" } ], somekey2: [ { id: "3456546", fee: "234", data: "23-11-2021" }, ], }
    • id将从apiData插入
    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    相关资源
    最近更新 更多