入门教程: 用 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;
}
进一步完善:
在 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;
在确定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>
)
});
将 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>;
}
在 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,
})
}
修改 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>
);
}
非常简单,只需判断 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仓库 里了。