[更新]简单的官方demo井字棋

This commit is contained in:
唐明明
2021-02-15 21:20:16 +08:00
parent 86a21a6c83
commit 001eb197a2
12 changed files with 212 additions and 15 deletions

View File

@@ -1,17 +1,139 @@
/**
* Web唐明明
* 匆匆数载恍如梦,岁月迢迢华发增。
* 碌碌无为枉半生,一朝惊醒万事空。
* ComponentName: '官方demo - 组件之间的传参'
*/
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// 类组件
// class Square extends React.Component {
// // 入口函数
// render() {
// return (
// <button
// className="square"
// onClick={() => this.props.onSquare()}
// >
// {this.props.value}
// </button>
// );
// }
// }
// 函数组件
const Square = (props) => {
return (
<button
className="square"
onClick={props.onSquare}
>
{props.value}
</button>
)
}
class Board extends React.Component {
// 类组件es6的constructor钩子函数
constructor (props) {
super(props);
this.state = {
squares: Array(9).fill(null),
xInNext: true
}
}
// 定一个一个组件方法
handleClick(i) {
// Array.slice()返回数组选定的元素,相当于克隆了原有数组
const squares = this.state.squares.slice()
if(calculateWinner(squares) || squares[i]) {
return
}
squares[i] = this.state.xInNext ? 'X': 'O'
this.setState({
squares,
xInNext: !this.state.xInNext
})
}
// 小方格方法
renderSquare(i) {
return <Square
value={this.state.squares[i]}
onSquare={()=>this.handleClick(i)}
/>;
}
render() {
const winner = calculateWinner(this.state.squares)
let status;
if (winner) {
status = '恭喜选手' + winner + '获胜~'
}else{
status = '下一位选手: ' + (this.state.xInNext ? 'X': 'O');
}
return (
<div>
<div className="status">{status}</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 {
render() {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info">
<div>{/* status */}</div>
<ol>{/* TODO */}</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 squares[a];
}
}
return null;
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
<Game />,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();