1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > React 官网入门教程 - 井字棋小游戏

React 官网入门教程 - 井字棋小游戏

时间:2024-04-18 20:44:39

相关推荐

React 官网入门教程 - 井字棋小游戏

刚刚开始学习 React,跟着官网的小教程做了一遍,还做了一些代码的精简和修改

官网教程地址:点击跳转到官网

最终效果:

import React from 'react'import ReactDOM from 'react-dom'import './index.css'const Square = props => <button className="square" onClick={props.onClick} >{props.value}</button>const Board = props => (<>{[0, 1, 2].map(i => (<div className="board-row" key={i}>{[0, 1, 2].map(j => <Square value={props.squares[i * 3 + j]} onClick={() => props.onClick(i * 3 + j)} key={i * 3 + j} />)}</div>))}</>)class Game extends ponent {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]) returnsquares[i] = this.state.xIsNext ? 'X' : 'O'this.setState({history: [...history, {squares}],xIsNext: !this.state.xIsNext,stepNumber: history.length})}jumpTo(step) {this.setState({stepNumber: step,xIsNext: (step % 2) === 0})}render() {const history = this.state.historyconst current = history[this.state.stepNumber]const winner = calculateWinner(current.squares)let status = winner ? `Winner: ${winner}` : `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 key={move}><button onClick={() => this.jumpTo(move)}>{desc}</button></li>)})return (<div className="game"><div className="game-board"><Boardsquares={current.squares}onClick={i => this.handleClick(i)}/></div><div className="game-info"><div>{status}</div><ol>{moves}</ol></div></div>)}}ReactDOM.render(<Game />,document.getElementById('root'))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}

body {font: 14px "Century Gothic", Futura, sans-serif;margin: 20px;}ol, ul {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;line-height: 34px;height: 34px;margin-right: -1px;margin-top: -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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。