开始学习React——跟着官网做井字棋

官网教程

入门教程: 用 React 做井字棋游戏
React 概念学习

代码

基础部分:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }
  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(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}]),
      xIsNext: !this.state.xIsNext,
      stepNumber: history.length,
    });
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: step % 2 === 0,
    })
  }

  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    let status;
    if (winner) {
      status = 'Winner: ' + winner;
    }
    else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }

    const moves = history.map((step, move) => {
      const desc = move ? 
        'Go to move #' + move :
        'Go to game start';
      return (
        <li>
          <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      )
    });

    return (
      <div className="game">
        <div className="game-board">
          <Board 
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}

// ========================================
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Game />);

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}

进一步完善:

1. 历史记录中添加坐标显示

在 history 中添加 coordinate 属性,初值设为 ‘’

history: [{
        squares: Array(9).fill(null),
        coordinate: '',
      }],

在处理点击时生成坐标并更新到 history 中

let coordinate = squares[i] + '(' + parseInt(i/3) + ',' + (i%3) + ')';

在渲染历史记录时添加坐标显示

const desc = (move ? 'Go to move #' + move : 'Go to game start') 
				+ ' ' + step.coordinate;

在这里插入图片描述

2. 在历史记录列表中加粗显示当前选项

在确定moves列表元素时判断索引与stepNumber是否一致,据此设置样式

const moves = history.map((step, move) => {
      const desc = (move ? 
        'Go to move #' + move :
        'Go to game start') + ' ' + step.coordinate;
      let textStyle = {};
      if (move === this.state.stepNumber) {
        if (winner) textStyle = {color: 'red', fontWeight: 'bold'};
        else textStyle = {fontWeight: 'bold'};
      }
      return (
        <li>
          <button onClick={() => this.jumpTo(move)} style={textStyle}>{desc}</button>
        </li>
      )
    });

在这里插入图片描述

3. 双重循环渲染棋盘

将 Board 的 render 函数修改为循环表示

render() {
    let board = [];
    for (let i = 0; i < 3; i++) {
      let row = [];
      for (let j = 0; j < 3; j++) 
        row.push(this.renderSquare(i*3+j));
      board.push(<div className='board-row'>{row}</div>)
    }
    return <div>{board}</div>;
  }

利用数组内置的 map 函数可以得到更简短的写法

render() {
    return <div>{
      [0, 1, 2].map(
        (i) => <div className='board-row'>{
            [0, 1, 2].map((j) => this.renderSquare(i*3+j))
          }</div>
      )
    }</div>;
  }

4. 添加历史记录正反序按钮

在 Game 的 state 中添加 order 属性,初始化为 false

this.state = {
      history: [{
        squares: Array(9).fill(null),
        coordinate: '',
      }],
      xIsNext: true,
      stepNumber: 0,
      order: false,
    }

生成历史记录数组时根据 order 来判断是否翻转数组

if (this.state.order) moves.reverse();

添加改变顺序的按钮,绑定对应函数

<button onClick={() => this.changeOrder()}>{this.state.order?'▲':'▼'}</button>
changeOrder() {
    this.setState({
      order: !this.state.order,
    })
  }

在这里插入图片描述

5. 高亮连成一线的三颗棋子

修改 calculateWinner,使其返回连线三棋子的位置信息

if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return {player: squares[a], position: lines[i]};
    }

当检测到胜利时保存信息

let status, highlights=[];
    if (winner) {
      status = 'Winner: ' + winner.player;
      highlights = winner.position;
    }

将该信息传入 Board 组件中

<Board 
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
            highlights={highlights}
          />

在调用 Square 组件时判断对应位置是否应高亮并传入该判断

renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
        highlight={this.props.highlights.includes(i)}
      />
    );
  }

根据高亮信息调整按钮内容样式

function Square(props) {
  let style = null;
  if (props.highlight) style = {color: 'red'};
  return (
    <button className="square" onClick={props.onClick} style={style}>
      {props.value}
    </button>
  );
}

在这里插入图片描述

6. 无人获胜时显示平局

非常简单,只需判断 stepNumber 到第九步时是否有人获胜,没人获胜就更改 status 显示平局信息

if (winner) {
  status = 'Winner: ' + winner.player;
  highlights = winner.position;
}
else if (this.state.stepNumber < 9) {
  status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
}
else status = 'It\'s a tie!';

在这里插入图片描述

完整代码

放在 github仓库 里了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
React中父组件向子组件传值可以通过props实现,而子组件向父组件传值可以通过回调函数实现。 假设我们有一个父组件Modal,其中包含一个子组件Form,我们希望在Form表单中填写完数据后,将数据传递给Modal组件进行处理。 首先,我们在Modal组件中定义一个state,用来保存Form表单中的数据: ```javascript class Modal extends React.Component { constructor(props) { super(props); this.state = { formData: {} }; } // ... } ``` 然后,在Modal组件中定义一个函数,用来接收Form组件传递的数据,并更新Modal组件的state: ```javascript handleFormData = (data) => { this.setState({ formData: data }); } ``` 接下来,在render函数中,将handleFormData函数传递给Form组件作为props: ```javascript render() { return ( <div> <Form onFormData={this.handleFormData} /> </div> ); } ``` 在Form组件中,我们通过props接收父组件传递过来的onFormData函数,并在表单提交时调用该函数将数据传递给父组件: ```javascript class Form extends React.Component { handleSubmit = (event) => { event.preventDefault(); const data = { name: event.target.name.value, age: event.target.age.value }; this.props.onFormData(data); } render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" name="name" placeholder="姓名" /> <input type="text" name="age" placeholder="年龄" /> <button type="submit">提交</button> </form> ); } } ``` 注意,这里我们使用了event.target来获取表单中的数据,而不是使用refs或者state来获取数据,这是因为React不推荐直接操作DOM元素。 最后,当Form表单提交后,父组件的state中就会保存表单中的数据,我们可以在Modal组件中对数据进行处理或者展示。 这就是父子组件之间传值的基本方法,通过props和回调函数,可以轻松地实现组件之间的数据传递。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值