如何解决首先单击切换后禁用图像元素,然后在react挂钩中使用setTimeout重新启用它
我正在构建一个停车位功能,以便使用reservation time
向用户分配停车位。我想要实现的是,当用户first clicks
在图像元素上时,将图像toggles
转换为第二个图像,然后disables
切换功能一段时间(保留时间),为此,用户无法在预定时间到期之前第二次单击该图像元素。设置的超时将稍后将onClick
和toggle
模拟图像返回其初始状态。到目前为止,我已经在toggleActive()中使用了set timeout
,但是根据set timeout
的功能,切换状态并未按预期进行切换。这是到目前为止我所做的代码:
// === 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>
);
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。