J'utilise un formulaire antd pour créer une liste de tâches, chaque formulaire a un bouton "submit" et "cancel". Chaque fois que l'utilisateur crée une tâche, un nouveau formulaire est généré. Je garde le nombre de tâches comme identifiant de formulaire. Mais lorsque je change les champs, je dois récupérer l'ID du formulaire, mais l'ID du formulaire est mis à jour avec la valeur du nombre de tâches.
Créer Task.js
import React from "react";
import actions from "../redux/actions";
import store from "../redux/store";
import { Button } from 'antd';
import '../stylesheet/createTask.scss';
import {useSelector} from "react-redux";
import TaskForm from "./taskForm";
const CreateTask=()=>{
const addTask=useSelector((state)=>{
const {taskCount,task,templates}=state?.reducers
return {taskCount,task,templates}
})
const {taskCount,task,templates}=addTask;
const createTask=()=>{
templates.push(<div id={`task${taskCount+1}`} key={`template${taskCount}`}><TaskForm/></div>);
store.dispatch({type:actions.ON_ADD_TASK,payload:templates})
}
return(
<div className={"create-task"}>
<span className={"task-count"}>Task {taskCount} </span>
<Button onClick={createTask}>+</Button>
{templates && templates.map((data)=>data)}
</div>
)
}
export default CreateTask;
TaskForm.js
import React, {useEffect, useState} from "react";
import { Form, Input, Button, Select,TimePicker,DatePicker, Space } from 'antd';
import moment from 'moment';
import {useSelector} from "react-redux";
import actions from "../redux/actions";
import store from "../redux/store";
import tasks from "../redux/reducers";
const layout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 16,
},
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16,
},
};
const TaskForm = () => {
const [form] = Form.useForm();
const taskDetails=useSelector((state)=>{
const {taskCount,task}=state?.reducers
return {taskCount,task}
})
const [fields, setFields] = useState([
{ userData: {
task_msg:"",
assigned_user:"",
task_date: moment('2015-01-01', 'YYYY-MM-DD'),
task_time:moment('00:00:00', 'HH:mm:ss'),
time_zone: new Date().getTimezoneOffset(),
is_completed: 0,
}},
])
const userData = {
};
const{taskCount,task}=taskDetails;
const onFinish = (fieldsValue) => {
const values = {
...fieldsValue,
'task_date': fieldsValue['task_date'].format('YYYY-MM-DD'),
'task_time': fieldsValue['task_time'].format('HH:mm:ss'),
};
store.dispatch({type:actions.ON_SAVE_TASK,payload:values})
};
function onTimeChange(time, timeString) {
console.log(time, timeString);
}
function onDateChange(date, dateString) {
console.log(date, dateString);
}
const fieldsChange=(newFields)=>{
let id=newFields.target.id.split("_")[0].split("form")[1];
console.log("id", id);
console.log("new Fields", newFields.target.id)
setFields(newFields)
console.log("on field change" )
}
useEffect(()=>{
console.log("task Did update", task)
// setFields(tasks)
},[])
return (
<Form {...layout} form={form}
initialValues={userData}
name={`form${taskCount}`}
onChange={fieldsChange}
onFinish={onFinish}>
<Form.Item
label="Task Description"
name={"task_msg"}
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
label="Task Description"
name="task_date"
rules={[
{
required: true,
},
]}
>
<Space direction="vertical">
<DatePicker onChange={onDateChange} defaultValue={ moment('2015-01-01', 'YYYY-MM-DD')} />
</Space>
</Form.Item>
<Form.Item
label="Task Description"
name={"task_time"}
rules={[
{
required: true,
},
]}
>
<Space direction="vertical">
<TimePicker onChange={onTimeChange} defaultValue={moment('00:00:00', 'HH:mm:ss')} />
</Space>
</Form.Item>
<Form.Item
name="assigned_user"
label="Assigned User"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="secondary" htmlType={"button"} >
Cancel
</Button>
</Form.Item>
</Form>
);
};
export default TaskForm;
Reducers.js :
import actions from "./actions";
const stateInit={
taskCount:0,
task:[],
userData:{
task_msg: '',
task_date: '',
task_time: 36000,
assigned_user: '',
time_zone: new Date().getTimezoneOffset(),
is_completed: 0,
},
templates:[],
};
export default function tasks(state=stateInit, action){
switch (action.type){
case actions.ON_ADD_TASK:{
return {...state,
taskCount: state.taskCount+1,
task:[...state.task,{userData:{...state.userData}}],
templates:action.payload,
};
}
case actions.ON_SAVE_TASK:{
return {
...state,
task:[]
}
}
default:{
return {
...state
}
}
}
}
L'identifiant du formulaire est mis à jour avec le nombre de tâches. Référez-vous à l'image :