映射数组时在 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 (将#修改为@)