如何解决映射数组时在 React 中切换 className
在映射数组时切换类时遇到问题。
我有一系列产品。
export const Products = [
{
id: 0,img: 'Star Wars',title: 'Star Wars: Battlefront',description: 'Immerse Yourself in the Ultimate Star Wars
Experience.',price: 300,isInBasket: false
},
我使用 useContext 来传递数据
const GamesProvider = ({ children }) => {
const [games,setGames] = useState(Products);
return (
<GamesContext.Provider value={{ games }}>
{children}
</GamesContext.Provider>
);
};
在这里我映射数组以显示元素,我想通过 props game.isInBasket 在 div products__game 中切换类
const productsList = gameCtx.games.map(game => (
<div className={`products__game ${game.isInBasket ? '' : 'disabledd'}`} key={game.id}>
<div className="products__game__image">
<span>{game.img}</span>
</div>
<div className="products__game__description">
<div className="products__game__description-container">
<h3>{game.title}</h3>
<span>{game.description}</span>
<span>{game.price} Gil</span>
</div>
<button onClick={() => addProductToBasket(game.id)}>Add to Basket</button>
</div>
</div >
));
addProductToBasket
const addProductToBasket = (id) => {
const addProduct = gameCtx.games.find(el => el.id === id);
cartCtx.addGame(addProduct)
};
添加游戏
const cartReducer = (state = defaultCartState,action) => {
if (action.type === 'ADD') {
const updatedTotalAmount = state.totalAmount + Number(action.game.price);
const game = action.game
const updatedGame = {
...game,isInBasket: true,}
const updatedGames = state.games.concat(updatedGame);
return {
games: updatedGames,totalAmount: updatedTotalAmount,}
}
...
当我将产品添加到购物篮时,“isInBasket”字段已更改为 true,当我删除游戏时为 false,因此一切正常,但 div 无法获得该类。
<div className={`products__game ${game.isInBasket ? '' : 'disabledd'}`} key={game.id}>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。