How to create and store values of multiple inputs in a dynamic form?

自古美人都是妖i 提交于 2020-03-04 21:36:05

问题


I have a form where user can generate new inputs to the form he wants to submit, however i am stuck on handling the values of the new generated inputs as i need to store them in the state.

My code

const [supply_detail_data,setSupply_detail_data]=React.useState({
    suppCashDetail:[{text : [],val:[]}]
});

const addNewSuppDetailInput = () => {
    setSupply_detail_data(
        {suppCashDetail: [...supply_detail_data.suppCashDetail,{text : [],val:[]}]}
    )
}

function supply_detail_handler(event){
    // should store the values of inputs in the State
}

JSX

<div className='addNewInput' onClick={addNewSuppDetailInput}>+</div>
 {
    supply_detail_data.suppCashDetail.map((el,index) => {
    let textID='suppDetailText'+index;
    let valID='suppDetailVal'+index;
        return (
        <div key={index}>
        •<input type='text' 
            name={textID}
            value={el.text||''} 
            onChange={supply_detail_handler.bind(index)}
        />

        <input type='number'
            name={valID} 
            value={el||''} 
            onChange={supply_detail_handler.bind(index)}/> 
        </div>
        );

    }) 
 }

Each time the user press on the + two inputs generated, one of type text the other of type number,I need to know how the supply_detail_handler that is executed on value change to store the value of new generated inputs


回答1:


What you need is to assign every input a unique identifier that later you can use in you store. Check this example: https://codesandbox.io/s/muddy-firefly-xz31w



来源:https://stackoverflow.com/questions/60132525/how-to-create-and-store-values-of-multiple-inputs-in-a-dynamic-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!