[英]React Redux: Different actions for list items
我有一個由 React 組件組成的列表:
<div className="card-list">
{cards.map((card, i) => (
<Card card={card} key={card.cardId} index={i}/>
))}
</div>
問題是點擊一張卡片應該為被點擊的卡片打開一個模態 window 。 要調用模態 window 我在 Card 組件中使用以下代碼:
const Card = ({card, key, index}) => {
const dispatch = useDispatch();
const showModal = useSelector(state => state.modal.showContentModal);
return (
<div>
//this is card view
<div onClick={() => dispatch(showContentModal())}>
<h3>{card.name}</h3>
</div>
//this is modal window
<div id={`modal-overlay-container-${key}`} className={`modal-overlay ${showModal && "active"}`}>
<div id={`modal-div-${key}`} className={`modal ${showModal && "active"}`}>
<p className="close-modal" onClick={() => dispatch(hideContentModal())}>
<svg viewBox="0 0 20 20">
<path fill="#8e54e9" d="..."/>
</svg>
</p>
<div className="modal-content">
<CardContent card={card} index={index}/>
</div>
</div>
</div>
</div>
)
}
export default Card;
showСontentModal()
操作更改了 Boolean 標志,這使得模態 window active
,而hideModalContent()
則相反。 但是由於列表中的所有組件都鏈接到單個操作,因此單擊任何卡都會為所有組件打開一個模態 window。 有沒有辦法只為特定卡觸發動作?
我看到有兩種方法可以解決這個問題。
state.modal.showContentModal
如果您在其他組件中不需要state.modal.showContentModal
,那么我更喜歡第一個選項。
const [showModal, setShowModal] = useState(false)
const handleOpenModal = () => setShowModal(true)
<div onClick={handleOpenModal}>
<h3>{card.name}</h3>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.