【发布时间】:2021-01-23 09:47:19
【问题描述】:
尝试将图像加载到反应中,这只是一个测试,最终我将把它全部保存在一个数组中,该数组保存为用于切换的数据。但是我无法加载图像我经常找不到模块,我已经安装了 url 和文件加载器,我尝试将图像文件夹放在不同的位置,它目前在 src 中。我可以从我的 CSS 文件中加载相同的图像作为背景。
import React, { useState } from 'react';
import Scoreboard from './Scoreboard';
import './CSS/Game.css';
import Data from './Data';
import geeAtherton from '../Images/gee-atherton.png';
const Game = (props) => {
const riders = Data;
const [score, setScore] = useState(0);
const [highScore, setHighScore] = useState(0);
const [cardOne, setCardOne] = useState(riders[0]);
const [cardTwo, setCardTwo] = useState(riders[1]);
const [cardThree, setCardThree] = useState(riders[2]);
/* Plays on click and checks answer
NEED TO REQUIRE SCORE UPDATE
*/
function playRound(choice){
console.log(choice)
if (!riders[choice].used){
setScore(score +1);
riders[choice].used = true
}else{
alert('loser')
newGame();
}
if (score === 4){
alert('Jeez Louise you win!')
newGame();
}
else {
setCards();
}
}
/*checks to ensure at least one card hasn't been picked
and then sets the new card values*/
function setCards(){
shuffle(riders)
if (riders[0].used === true && riders[1].used === true && riders[2].used === true){
setCards();
}
else {
setCardOne(riders[0]);
setCardTwo(riders[1]);
setCardThree(riders[2]);
}
}
/* Resets the game*/
function newGame(){
for(let i = 0; i < riders.length; i++){
if (riders[i].used === true){
riders[i].used = false;
}
}
if (score > highScore){
setHighScore(score);
}
setScore(0);
setCards();
}
/* Shuffle the array */
function shuffle(array){
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
}
return (
<div>
<Scoreboard score = {score}
highScore = {highScore}/>
<div id = "game-container">
<div className = "card" onClick = {() => playRound(0)}>
<img src = {require(geeAtherton)} alt ={cardOne.name}></img></div>
<div className = "card" onClick = {() => playRound(1)}>{cardTwo.id}</div>
<div className = "card" onClick = {() => playRound(2)}>{cardThree.id}</div>
</div>
</div>
)
}
export default Game
【问题讨论】:
标签: javascript reactjs