{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
);
}
}
class Game extends React.Component {
constructor (props) {
super(props)
this.state = {
history: [{
squares: Array(9).fill(null)
}],
xIsNext: true,
stepIndex: 0
}
}
// 定一个一个组件方法
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepIndex + 1)
const current = history[history.length - 1]
const squares = current.squares.slice()
if(calculateWinner(squares) || squares[i]){
return
}
squares[i] = this.state.xInNext ? 'X': 'O'
this.setState({
history: history.concat([{ squares }]),
xInNext: !this.state.xInNext,
stepIndex: history.length
})
// Array.slice()返回数组选定的元素,相当于克隆了原有数组
}
jumpTo(index){
this.setState({
stepIndex: index,
xIsNext: (index % 2) === 0,
})
}
render() {
const history = this.state.history
const current = history[this.state.stepIndex]
const winner = calculateWinner(current.squares)
const moves = history.map((stepArr, index) => {
const desc = index ? '下一步' + index : '开始游戏'
return(