1

我正在制作一个游戏,我需要不同风格的选定(按下)项目。如果单击该 div,我正在尝试将“选定”类附加到 div。换句话说,我有一个状态:

const [pressedGifId, gifPressed] = useState(null);

什么时候

pressedGifId === gifId

那么我应该将“选定”类附加到我的 div 中。这是我的简化代码:

import React, { useState, useEffect } from 'react';

export default function Game() {
  const addedToGameGif = [];

  const [pressedGifId, gifPressed] = useState(null);
  const [photoCards] = useState([]);

  useEffect(() => {
    console.log(pressedGifId);
  }, [pressedGifId]);

  if (photoCards.length === 0) {
    for (let i = 0; i < 5; i += 1) {
      addedToGameGif.push([i, 'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg']);
    }
  }

  addedToGameGif.map(item =>
    photoCards.push(
      <div key={item[0]}>
        <div
          onClick={() => gifPressed(`gif${item[0]}`)}
          className={`${pressedGifId === `gif${item[0]}` && 'selected'}`}
        >
          <img src={item[1]} alt="bla" width="300" height="180" />
        </div>
        <br />
      </div>,
    ),
  );
  return <div>{photoCards}</div>;
}

我看不到根据状态更新的类:(它保持为空)

f12 视图

但是我在控制台中获得了更新的状态(我在 useEffect 中打印它):

控制台视图

我的目标:

1)点击改变状态(pressedGifId)

2) 如果pressedGifId 与当前映射的项目id ( gif${item[0]})匹配,则将“selected”类添加到div

更新2:

提供的解决方案对我不起作用,因为我的照片卡是随机挑选的照片,并且提供的解决方案照片在每次点击时都会变成新的随机挑选的照片(我不想这样)。但这让我得到了正确的答案:

我将 photoCards 置于一个状态(钩子)并将其设置为第一次加载(当 photoCards 数组长度为 0 时)。它阻止重新加载并且类工作。

这是更新的代码:

    export default function Game(props) {

    const [pressedGifId, setGifPressed] = useState(null);
    const [gifCards, setGifCards] = useState([]);

    useEffect(() => {
        if (gifCards.length === 0) 
          setGifCards(randGen.getGifArray());
    }

      const renderCards = () =>
      gifCards.map((item, index) => {
      const gifId = `gif${item[0]}`;

      return (
        <div key={item[0]}>
          <div
            onClick={() => setGifPressed(gifId)}
            onKeyPress={() => setGifPressed(gifId)}
            role="button"
            tabIndex="0"
            className={`card ${getClass(gifId)}`}
          >
            <img
              src={item[1]}
              alt={txtCards[index][1]}
              width="300"
              height="180"
            />
          </div>
        </div>
      );
    });

     return (
       <div>
          {renderCards()}
        </div>
      );
   }



4

2 回答 2

2

这是我改变的那一行。

className={pressedGifId === `gif${item[0]}` ? "selected" : ""}

整个代码。

import React, { useState, useEffect } from "react";
import "./styles.css";
export default function Game() {
  const addedToGameGif = [];

  const [pressedGifId, gifPressed] = useState(null);
  let photoCards = [];

  useEffect(() => {
    console.log("->", pressedGifId);
  }, [pressedGifId]);

  if (photoCards.length === 0) {
    for (let i = 0; i < 5; i += 1) {
      addedToGameGif.push([
        i,
        "https://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg"
      ]);
    }
  }

  photoCards = addedToGameGif.map(item => (
    <div key={item[0]}>
      <div
        onClick={() => gifPressed(`gif${item[0]}`)}
        className={pressedGifId === `gif${item[0]}` ? "selected" : ""}
      >
        <img src={item[1]} alt="bla" width="300" height="180" />
        {console.log(item)}
      </div>
      <br />
    </div>
  ));

  console.log("-", photoCards, addedToGameGif);
  return <div>{photoCards}</div>;
}

这是有效的。我试过了,检查这个JS 片段

于 2020-01-22T12:36:41.630 回答
2
import React, { useState, useEffect } from 'react';

const Game = () => {

  //here we are passing our gif data 
  const gifData = [
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg',
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg',
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg',
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg',
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg' 
  ]

  // pressedGifId : for gifId selection
  const [pressedGifId, setGifPressed ] = useState(0);

  // renderPhotoCards : this function return all cards 
  // onClick :   setGifPressed to clicked gifId 
  // className : if our index of perticuler gif match with pressedGifId then we are setting it as selected

  const renderPhotoCards = () => 
    gifData.map(( item , index )  => (
      <div key={index}>
        <div
          onClick={() => setGifPressed(index)}
          className={  pressedGifId === index ? `gif${index} selected` : `gif${index}`  }
        >
          <img src={item} alt="bla" width="300" height="180" />
        </div>
        <br />
      </div>
    )
  )

  return renderPhotoCards()

}

export default Game;
于 2020-01-22T11:21:37.087 回答