如何在React中获取表单的值



我试图在React的表单中获得所有输入元素的值。这是我的表单


export default function MarkAttendance() {
const dispatch = useDispatch();
const navigate = useNavigate();
const { users, loading, error } = useSelector((state) => state.userList);
const today = new Date().toISOString().substr(0, 10);
const { userInfo } = useSelector((state) => state.userLogin);
const [firstTime, setFirstTime] = useState('')
const [secondTime, setSecondTime] = useState('')
const [attenandance, setAttendance] = useState({ id: null, date: today, first_time: "Present", second_time: "Present" });
useEffect(() => {
if (userInfo && userInfo.isAdmin) {
dispatch(listUsers());
} else {
navigate("/login");
}
}, [dispatch, userInfo, navigate]);
const handleSubmit = (e) => {
e.preventDefault();

for (let i = 0; i < users.length; i++) {
setAttendance({ id: users[i].id, date: today, first_time: firstTime, second_time: secondTime });
postAttendance(attenandance);
}
}
return (
<section>
<div className="row">
<div className="col-md-12 text-dark">
<h3>Mark Attendance</h3> for <h4>{today}</h4>'s meal
</div>
</div>
{loading ? (
<Loader />
) : error ? (
<Message variant="danger">{error}</Message>
) : (
<form onSubmit={handleSubmit}>
<table className="table table-bordered">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Room no.</th>
<th scope="col">First Time</th>
<th scope="col">Second Time</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>

<th scope="row" name="userId">{user.id}</th>
<td className="form-group">
<input
type="text"
className="form-control"
id="table-name"
name="username"
value={user.username}
/>
</td>
<td className="form-group">
<input
type="text"
className="form-control"
id="table-room"
name="room"
value={user.room}
/>
</td>
<td>
<select name={`firstAttendance${user.id}`} onChange={(e) => (e.target.value)} className="form-control" id="table-first-time">
<option value="present">Present ✓</option>
<option value="absent">Absent X</option>
<option value="double">Double 2</option>
</select>
</td>
<td>
<select name={`secondAttendance${user.id}`} onChange={(e) => (e.target.value)} className="form-control" id="table-second-time">
<option value="present">Present ✓</option>
<option value="absent">Absent X</option>
<option value="double">Double 2</option>
</select>
</td>
</tr>
))}
</tbody>
</table>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>
)}
</section >
);
}

我想要的是与用户id一起获得选择值并将其发送回服务器。我不知道如何获得用户id和他在表单中选择了什么。它是由map函数生成的这意味着name属性都是相同的

What I have try

  1. 我试图动态地改变name属性,但它仍然给我未定义。
  2. 我尝试使用useState钩子,但它只给我最后一个用户的值,这也改变了其他用户的值,因为只有一个钩子。

那么如何在reactjs中获得表单中的所有值。由于

所以过了一段时间后,我终于使用了这个技巧来获取所有的值。我所做的是给每个input标签一个单独的id,通过将每个用户的user-id合并到input标签id中。因为每个用户都有一个唯一的id,所以输入和选择标签也是如此。然后通过提供user-id来提取所需输入first_timesecond_time的值,循环遍历每个输入并获得所有用户的单独值,并将它们分派到postAttendance上。下面是它的样子:


const handleSubmit = (e) => {
e.preventDefault();
try {
const attendanceExtractor = (e, id) => {
let first_time = e.target.elements[`first-attendance-${id}`].value;
let second_time = e.target.elements[`second-attendance-${id}`].value;
return [first_time, second_time]
}  // writing a separate function for extracting each value

// then looping through each 
for (let index = 0; index < userIds.length; index++) {
let id = userIds[index];
const attendance = {
student: id,
date: date,
first_time: attendanceExtractor(e, id)[0],
second_time: attendanceExtractor(e, id)[1]
}
dispatch(postAttendance(attendance, id))
}
alert("All the attendance is submitted successfully")
dispatch(getAttendance());
let count = counter(getAttendanceObj, date);
setTotal(count)
console.log(count)
} catch (error) {
}
}

和表单看起来像这样:

<form className="form" onSubmit={handleSubmit}>
<table className="table table-bordered">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Room no.</th>
<th scope="col">First Time</th>
<th scope="col">Second Time</th>
<th scope="col">Status</th>
</tr>
</thead>
{users.map((user) => (

<tbody>


<tr key={user.id}>

<th scope="row" id={`user-id-${user.id}}`}>{user.id}</th>
<td className="form-group">
<input
type="text"
className="form-control"
id={`table-name-${user.id}`}
name="username"
value={user.username}
/>
</td>
<td className="form-group">
<input
type="text"
className="form-control"
id={`table-ropm-${user.id}`}
name="room"
value={user.room}
/>
</td>
<td>
<select id={`first-attendance-${user.id}`} onChange={(e) => (e.target.value)} className="form-control" >
<option value="present">Present ✓</option>
<option value="absent">Absent X</option>
<option value="double">Double 2</option>
</select>
</td>
<td>
<select id={`second-attendance-${user.id}`} onChange={(e) => (e.target.value)} className="form-control" > // FOCUS ON ID
<option value="present">Present ✓</option>
<option value="absent">Absent X</option>
<option value="double">Double 2</option>
</select>
</td>
<td>
<i class="bi bi-check" ></i>
</td>
</tr>
</tbody>
))
}
</table>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>

最新更新