我正在使用一个下拉菜单为记忆游戏选择不同的级别。我正在使用if / elseif语句,因为其中涉及三个变量。它的控制台从Gameboard组件记录了正确的结果,但是我无法在Title组件中加载正确的关卡名称,我也不知道为什么。我想我需要状态对象才能使其正常工作。
我尝试使用CSS生成文本,将对象转换为数组(在第二个菜单选择上,这将Title的每个字母转换为数组元素,然后炸毁了应用程序),甚至尝试传递级别将标题添加到标题组件中,但没有任何效果。我仍在弄清楚使用组件的复杂性。谢谢!
这是if / elseif
let gameLevel = <div>Level One</div>;
let cards = 18;
let colWidth = 2;
const level = (this.props.type);
console.log(level);
if (level === 'first') {
gameLevel = <div>Level One</div>;
cards = 18;
colWidth = 2;
} else if (level === 'second') {
gameLevel = <div>Level Two</div>;
cards = 12;
colWidth = 3;
} else if (level === 'third') {
gameLevel = <div>Level Three</div>;
cards = 8;
colWidth = 3;
} else if (level === 'fourth') {
gameLevel = <div>Level Four</div>;
cards = 18;
colWidth = 2;
} else if (level === 'fifth') {
gameLevel = <div>Level Five</div>;
cards = 12;
colWidth = 3;
} else if (level === 'sixth') {
gameLevel = <div>Level Six</div>;
cards = 8;
colWidth = 3;
} else {
console.log(gameLevel, cards, colWidth);
}return gameLevel;
这是标题组件(在尝试修复此问题时,我也通过了props而不是newLevel)
const title = (newLevel) => {
console.log(newLevel);
const changeLevel = Object.keys(newLevel);
console.log(changeLevel);
return (
<div className={classes.Title}>
{changeLevel}
</div>
)
};
This is the gameboard component (I left out the cards)
class Gameboard extends Component {
state = {
levels: {
first: 'Level One',
second: 'Level Two',
third: 'Level Three',
fourth: 'Level Four',
fifth: 'Level Five',
sixth: 'Level Six'
},
cardCount: {
first: 18,
second: 12,
third:8,
fourth: 18,
fifth: 12,
sixth: 8
},
width: {
first: 2,
second: 3,
third: 3,
fourth: 2,
fifth: 3,
sixth: 3
}
};
changeBoard = (type) => {
const newLevel = this.state.levels[type];
const newCount = this.state.cardCount[type];
const newWidth = this.state.width[type];
console.log(newLevel);
console.log(newCount);
console.log(newWidth);
return <Title levels={newLevel}/>;
render () {
return (
<div>
<Row>
<Col className={classes.stats}>
<Menu changed={this.changeBoard}/>
</Col>
<Col>
<p className={classes.stats}>Matches<br/>0</p>
</Col>
<Col>
<p className={classes.stats}>Attempts<br/>0</p>
</Col>
<Col>
<p className={classes.stats}>Accuracy<br/>0</p>
</Col>
<Col>
<p className={classes.stats}>Wins<br/>0</p>
</Col>
<Col className={classes.stats}>
<button type='button' className='btn btn-danger btn-sm'>Reset</button>
</Col>
</Row>
<Timer/>
<Title levels={this.state.levels}/>
//cards here
</div>
)
}
};
export default Gameboard;
和渲染中...
<Title levels={this.state.levels}/>
我希望在菜单中选择LevelOne时在标题组件中看到“ Level 1”,而在选择Level 2时则看到“ Level 2”。取而代之的是,我得到一个静态的“ Level One”,“ Level One1”,所有的级别标题一次出现,“ Level One”由于状态对象而显示了23次,或者应用程序崩溃。