代码更改为更新循环中的特定字段。如果您想更新其他字段,您可以按照相同的方式进行操作。
将 ID 和事件传递给函数
<input
name="roomRent"
type="text"
value={roomData.room}
className={classes.input}
onChange={(e) => handleroom(e, i)}
/>
更新特定字段值的函数
const handleroom = (e, id) => {
const { value } = e.target;
setRooms((room) =>
room?.map((list, index) =>
index === id ? { ...list, room: value } : list
)
);
};
改进的代码
export default function RoomListView() {
const classes = useStyles();
const [roomes, setRooms] = useState([...rooms]);
const handleroom = (e, id) => {
const { value } = e.target;
setRooms((room) =>
room?.map((list, index) =>
index === id ? { ...list, room: value } : list
)
);
};
return (
<>
<div className={classes.root}>
<Paper className={classes.paper} variant="outlined" elevation={0}>
<div className={classes.layout}>
<div className={classes.main1}>
<Grid container>
<Grid item sm={3}>
<div className={classes.roomType}>
<h4 className={classes.roomTypeContent}>Room Rate</h4>
</div>
</Grid>
<Grid item sm={9}>
<div className={classes.Roomcalendar}>
{roomes.map((roomData, i) => {
return (
<>
<div className={classes.Roomview}>
<div
key={roomData.id}
className={classes.roomavailable}
>
<input
name="roomRent"
type="text"
value={roomData.room}
className={classes.input}
onChange={(e) => handleroom(e, i)}
/>
</div>
<div className={classes.roomSold}>
<p>{roomData.sold} Sold</p>
</div>
</div>
</>
);
})}
</div>
</Grid>
</Grid>
</div>
</div>
</Paper>
</div>
</>
);
}
实时工作代码