[英]REACT Cannot find module for images
嘗試將圖像加載到反應中,這只是一個測試,最終我將把它全部保存在一個數組中,該數組保存為用於切換的數據。 但是我無法加載圖像我經常找不到模塊,我已經安裝了 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
您不需要在img
標簽中使用require
。
<img src = {geeAtherton} alt ={cardOne.name}></img>
我會在我的公共文件中創建一個名為 images 的文件夾。 public/images
我會在public/images/gee-atherton.png
atherton.png 中保存gee-atherton.png
atherton.png,然后通過它的 url 調用它。
<img src='/images/gee-atherton.png' alt={cardOne.name}></img>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.