開發時有時需要動態添加輸入框,如下圖:
點擊添加周期,白框會被復制,開始看到這個功能是懵的,后來想明白了,本質就是渲染了一個數組,添加周期按鍵是向數組追加一個空對象,也可以帶有部分默認屬性值。
每個白框中修改數據的表單元素的onChange事件 ,都必須傳遞index,這樣就會根據index找到數組中的數據,進而修改,然后調用set函數
function cloneCheckBox(e,index) { let data = e.map(ele=>parseInt(ele)); weekStep[index].weekdays = data; setWeekStep([...weekStep]); } function handleTime(e,str,index,type) { weekStep[index][type] = str; setWeekStep([...weekStep]); }
渲染代碼:
<div className="classcontent"> {weekStep.map((ele,index)=>{ return <div className="repeatContent" key={index}> <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} name="周幾上課" label="周幾上課" valuePropName="checked"> <Checkbox.Group // onChange={e=>console.log(e)} onChange={(e) => { cloneCheckBox(e, index) }} options={checkOptions} /> </Form.Item> <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="上課時間" name="effectiveDataEnd" rules={[{ required: true, message: '請輸入終止日期!' }]} > <TimePicker onChange={(e, str) => { handleTime(e, str, index, 'startTime')}} defaultValue={moment(ele.startTime, 'HH:mm')} format={"HH:mm"} /> ~ <TimePicker onChange={(e, str) => { handleTime(e, str, index, 'endTime') }} defaultValue={moment(ele.endTime, 'HH:mm')} format={"HH:mm"} /> </Form.Item> </div> })} <Form.Item labelCol={{ span: 4 }} wrapperCol={{offset:4, span: 18 }} > <Button onClick={addWeekStep}>添加周期</Button> <Button onClick={testButton}>測試</Button> </Form.Item> </div>
參考文章:https://segmentfault.com/q/1010000017986817