1. 在游戏历史记录列表显示每一步棋的坐标,格式为 (列号, 行号)。
game.state.history中不仅需要记录棋盘,还需要记录此步落子的坐标
class Game extends React.Component {
// 修改Game构造函数中的history
constructor(props) {
super(props)
this.state = {
history: [{
squares: Array(9).fill(null),
stepIndex: null, // 增加这一行
}],
xIsNext: true,
stepNumber: 0,
}
}
// 点击的时候记录此步落子的坐标
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares: squares,
stepIndex: i, // 增加这一行
}]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
})
}
}
之后写一个函数式组件,用来展示棋子的坐标
function StepSpan(props){
const stepIndex = props.stepIndex
if(stepIndex !== null){
return (
<span>row:{
Math.floor(stepIndex/3) + 1}|col:{
stepIndex % 3 + 1}</span>
);
}
else{
return null
}
}
再修改Game的render方法中的moves
const moves = history.map((step, move) => {
const desc = move ?
'Go to move #' + move :
'Go to game start';
return (
<li key={
move}>
<button onClick={
() => this.jumpTo(move)}>{
desc}</button>
<StepSpan stepIndex={
step.stepIndex} ></StepSpan> // 增加这行