您好,我试图根据props.lives的值显示不同的子手照片。
import React from 'react';
import one from '../images/one.png';
import two from '../images/two.png';
import three from '../images/three.png';
import four from '../images/four.png';
import five from '../images/five.png';
import six from '../images/six.png';
import seven from '../images/seven.png';
import eight from '../images/eight.png';
import nine from '../images/nine.png';
import ten from '../images/ten.png';
import eleven from '../images/eleven.png';
import twelve from '../images/twelve.png';
const hangman = (props) => {
// const picture = new Array(props.lives).map(
// (_,i) => ( <span>{i}</span> )
// );
// const picture = [ ...Array(props.lives) ].map(
// (_,i) => ( <span key={i}>{++i}</span> )
// );
let hangmanImage = null;
switch (props.lives)
{
case 11:
hangmanImage={one};
break;
case 10:
hangmanImage={two};
break;
case 9:
hangmanImage={three};
break;
case 8:
hangmanImage={four};
break;
case 7:
hangmanImage={five};
break;
case 6:
hangmanImage={six};
break;
case 5:
hangmanImage = {seven};
break;
case 4:
hangmanImage = {eight};
break;
case 3:
hangmanImage = {nine};
break;
case 2:
hangmanImage = {ten};
break;
case 1:
hangmanImage = {eleven};
break;
case 0:
hangmanImage = {twelve};
break;
default:
hangmanImage = null;
}
return (
<img src={hangmanImage} />
);
}
export default hangman;
例如,如果我这样做,
return (
<img src={three} />
}
显示图像。但不是我这样做的时候,
return (
<img src={hangmanImage} />
}
我显示了残破的图像。顺便说一句,props.lives最初设置为12,但是如果在游戏中播放了错误的字母,则会由父组件递减。
我怀疑交换机内部的逻辑有问题吗?谢谢。
您在switch语句中有多余的花括号;您应该只将图像分配到hangmanImage
变量中:
switch (props.lives) {
case 11:
hangmanImage = one;
break;
case 10:
hangmanImage = two;
break;
case 9:
hangmanImage = three;
break;
...
}