在第一次点击toggle后禁用图像元素,然后在react钩子中使用setTimeout重新启用它



我正在构建一个停车位功能,以便使用reservation time为用户分配停车位。我试图实现的是,当用户first clicks在图像元素上时,图像toggles到第二个图像,然后disables在某个时间(预订时间(内切换功能,对于该时间,用户不能第二次点击图像元素,直到预订时间到期。设置的超时稍后将模拟onClicktoggle将图像恢复到其初始状态。到目前为止,我已经在toggleActive((中使用了set timeout,但根据set timeout的功能,toggle状态并没有按预期切换。以下是我迄今为止所做工作的代码:

// === toggleActive() === toggles the active image by id, selected by the user
function toggleActive(index) {
let arrayCopy = [...slotState.slots];
const countDownDate = new Date("September 4, 2020 00:00:00").getTime();

const now = new Date().getTime();
// duration === (Reservation time) === to reserve a parking slot
const reservationTime = countDownDate - now;

// if arrayCopy[index].toggled equals to true then toggled is *false* else toggled is *true*
arrayCopy[index].toggled
? setTimeout(()=>{
return(arrayCopy[index].toggled = false)},reservationTime)
: (arrayCopy[index].toggled = true);
changeState({ ...slotState, slots: arrayCopy });
}

function toggleActiveImage(index) {
if (slotState.slots[index].toggled) {
// === parkingImages.unavailable === is a red image(Indicating the slot is assigned)
return parkingImages.unavailable;
} else {
// === parkingImages.unavailable === is a blue image(Indicating the slot is not assigned)
return parkingImages.available;
}
}

const renderSlots = slotState.slots.map((slot, index) => {
return (
<div className="col-md-1" style={{ width: "auto" }} key={index}>
<img
key={index}
src={toggleActiveImage(index)}
style={{ width: "3rem", cursor: "pointer" }}
alt="parking"
onClick={() => toggleActive(index)}
/>
<p style={{ fontSize: ".8rem", fontWeight: "500" }}>
slot-{slot.slot_no}
</p>
</div>
);
});

我真的希望有一个解决上述问题的办法,提前谢谢你。

,我就是这么做的

const reservationTime = 3000;
const Slots = (props) => {
const [slots, setSlots] = React.useState(props.slots);
const disableSlot = (selectedIndex) => {
// Check if slot is active at the time of clicking.
if (slots[selectedIndex].active === true) {
const updatedSlots = slots.map((slot, index) => {
if (selectedIndex === index) {
slot.active = false;
}
return slot;
});
setSlots(updatedSlots);
setTimeout(() => {
activateSlot(selectedIndex);
}, reservationTime);
}
};
const activateSlot = (selectedIndex) => {
const updatedSlots = slots.map((slot, index) => {
if (selectedIndex === index) {
slot.active = true;
}
return slot;
});
setSlots(updatedSlots);
};
return (
<ul>
{slots.map((slot, index) => {
return (
<li key={slot.id} onClick={() => disableSlot(index)}>
{slot.name} - Active: {String(slot.active)}
</li>
);
})}
</ul>
);
};

相关内容

最新更新