【React】入门之官方例子井字棋“Tic Tac Toe”强化功能的实现(详解,附代码,文末有在线演示)

本文详细介绍了如何在React的井字棋官方示例中实现包括显示落棋位置、加粗历史步骤、动态改变棋盘输出、添加toggle按钮切换历史顺序、胜者格子高亮和平局提示等六项强化功能。通过修改Game和Board组件的render方法,增加新的逻辑和样式,实现了更丰富的交互体验。
摘要由CSDN通过智能技术生成

React入门之官方例子井字棋“Tic Tac Toe”强化功能的实现(详解,附代码)

前言

在Reactjs的这篇官方入门文档中,初学者会完成一个井字棋的小应用。在文档的最后,作者还给出了6个需求,分别为:

  1. Display the location for each move in the format (col, row) in the move history list.
  2. Bold the currently selected item in the move list.
  3. Rewrite Board to use two loops to make the squares instead of hardcoding them.
  4. Add a toggle button that lets you sort the moves in either ascending or descending order.
  5. When someone wins, highlight the three squares that caused the win.
  6. 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值