好久没看React了,最近又想重新看下。
除了视频课,前几天跟着官网的教程做了井字棋(tic-tac-toe),后面有一些可以改进游戏的想法,下面我就把这些自己练手的代码记录一下,这些功能是:
- 在游戏历史记录列表显示每一步棋的坐标,格式为 (列号, 行号)。
- 在历史记录列表中加粗显示当前选择的项目
- 使用两个循环来渲染出棋盘的格子,而不是在代码里写死(hardcode)
- 添加一个可以升序或降序显示历史记录的按钮
- 每当有人获胜时,高亮显示连成一线的 3 颗棋子
- 当无人获胜时,显示一个平局的消息。
P.S. 除了有注释的代码,其他原始功能我都是按照官网上的写的 先来各个组件的代码,最后再把全部代码贴在文末。 1. Square组件:没变化,跟官网代码一样 2. Board组件 3. Game 组件 4. calculateWinner方法 别忘了,涉及到样式变化,还有index.css的变化,就是补充一个样式: 以下是index.js的全部代码:
import React from 'react';
import ReactDOM from 'react-dom';
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
key={i}
value={this.props.squares[i]}
onClick={() => {
this.props.onClick(i)
}}
/>
}
render() {
return (
<div>
{
Array(3).fill(null).map((item1, index) => (
<div className="board-row" key={index}>
{
Array(3).fill(null).map((item2, index2) => (
this.renderSquare(3 * index + index2)
))
}
</div>
))
}
{}
</div>
)
}
}
class Game extends React.Component {
constructor(props) {
super(props)
this.state = {
history: [{
squares: Array(9).fill(null)
}],
xIsNext: true,
stepNumber: 0,
isHistorySort: true,
}
}
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,
lastIndex: i
}]),
xIsNext: !this.state.xIsNext,
stepNumber: history.length
})
}
jumpTo(step) {
for (let i = 0; i < 9; i++) {
document.getElementsByClassName('square')[i].style = ''
}
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0
})
}
order = () => {
this.setState({
isHistorySort: !this.state.isHistorySort
})
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares)
const moves = history.map((step, move) => {
const desc = move ?
'Go to #' + move + '最后落棋点(列号,行号):(' + parseInt(step.lastIndex / 3) + ',' + step.lastIndex % 3 + ')' :
'Go to game start'
return (
<li key={move}>
<button
onClick={() => this.jumpTo(move)}
className={move === this.state.stepNumber ? 'currentBtn' : ''}
>{desc}</button>
</li>
)
})
let status;
if (winner) {
status = 'winner: ' + winner.winnerName
for (let i of winner.winnerIndex) {
document.getElementsByClassName('square')[i].style = 'background: #ccc; color: #fff;'
}
} else {
if (this.state.history.length > 9) {
status = 'No player win! It ends in a draw!'
}
else {
status = 'Next Player: ' + (this.state.xIsNext ? 'X' : 'O')
}
}
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>
{}
<button onClick={this.order}>
{this.state.isHistorySort ? '倒序' : '正序'}
</button>
{}
{}
<ol> {this.state.isHistorySort ? moves : moves.reverse()} </ol>
</div>
</div>
)
}
}
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 {
winnerName: squares[a],
winnerIndex: [a, b, c]
}
}
}
return null
}
ReactDOM.render(<Game />, document.getElementById('root'))
以下是index.css的全部内容:
body{
font: 14px 'Century Gothic', Futura, sans-serif;
margin: 20px;
}
ol, li{
padding-left: 30px;
}
.board-row:after{
clear: both;
content: '';
display: table;
}
.status{
margin-bottom: 10px;
}
.square{
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
height: 34px;
line-height: 34px;
margin-top: -1px;
margin-right: -1px;
padding: 0;
text-align: center;
width: 34px;
}
.square:focus{
outline: none;
}
.kbd-navigation .square:focus{
background: #ddd;
}
.game{
display: flex;
flex-direction: row;
}
.game-info{
margin-left: 20px;
}
button.currentBtn{
font-weight: bold;
background: skyblue;
}
|