绑定一个key
const moves = history.map((step, move) => {
const said = move ?
'开始移动' + move : '开始游戏';
return ( <
li key={move}>
<
button onClick = {
() => this.eatJuzi(move)
} > { said } <
/button> </li >
)
Game 的构造函数 constructor 中向初始 state 中添加 stepNum: 0:
stepNum=0,
建立eatJuzi()函数
eatJuzi(step){
this.setState({
stepNum:step,
juziIsNext:(step%2)===0,
})
}
修改juziClick()函数
juziClick(i) {
const history = this.state.history.slice(0, this.state.stepNum + 1);
const current = history[history.length - 1];
const juzi = current.juzi.slice();
if (calculateWinner(juzi) || juzi[i]) {
return
}
juzi[i] = this.state.juziIsNext ? '大橘子' : '小橘子';
this.setState({
history: history.concat([{
juzi,
}]),
stepNum: history.length,
juziIsNext: !this.state.juziIsNext
})
}
修改Game中的render()
const history = this.state.history;
const current = history[this.state.stepNum];
const winner = calculateWinner(current.juzi);
其他不要动!!!
运行测试截图


完成!!!
谢谢

这篇博客详细介绍了在一款游戏中如何实现橘子的移动功能。通过在Game组件的构造函数中设置初始状态,定义eatJuzi函数来更新步数和橘子状态,并在juziClick函数中处理橘子的点击行为。同时,修改了render方法以展示历史步数和当前赢家。代码示例展示了关键的交互逻辑和状态管理。
1116

被折叠的 条评论
为什么被折叠?



