React入门之官方例子井字棋“Tic Tac Toe”强化功能的实现(详解,附代码)
文章目录
前言
在Reactjs的这篇官方入门文档中,初学者会完成一个井字棋的小应用。在文档的最后,作者还给出了6个需求,分别为:
- Display the location for each move in the format (col, row) in the move history list.
- Bold the currently selected item in the move list.
- Rewrite Board to use two loops to make the squares instead of hardcoding them.
- Add a toggle button that lets you sort the moves in either ascending or descending order.
- When someone wins, highlight the three squares that caused the win.
- When no one wins, display a message about the result being a draw.
本文会简单地分点介绍怎么实现它们(我的解决方法),完整的js代码在本文最后。
分点讲解
显示落棋位置
在历史数组的元素中,增加一个名为position
的属性,保存落棋的索引,再写一个getPosition
的方法,返回落棋的标准格式(列,行)。
Game的构造方法
constructor(props) {
super(props);
this.state = {
history: [
{
squares: Array(9).fill(null),
position: null,
}
],
stepNumber: 0,
xIsNext: true
};
}
getPosition函数
function getPosition(i) {
if (typeof i === 'number') {
let row = Math.floor(i / 3) + 1
let column = 1 + i - (row - 1) * 3
let position = '(' + column + ', ' + row + ')'
return position
} else {return ''}
}
加粗当前选择的历史步骤
首先增加一个样式
.current-step {
font-weight: bold;
}
在输出历史步骤的时候,如果步骤的索引和当前选择步骤一致,则添加上这个样式。
Game 的 render方法片段
if (move == currentStep) {
className = 'current-step'
} else {
className = ''
}
return (
<li key={move}>
<button className={className} onClick={() => this.jumpTo(move)}>{desc}{position}</button>
</li>
);
改变棋盘的输出方式,让其不再是硬编码输出
这里我们选择在JSX中调用数组的map方法双重循环输出棋盘,具体见代码:
Board 的render方法
render() {
const looper = [1, 2, 3];
var it = 0;
return (
<div>
{
looper.map((w