I am learning react and it just seems wrong to have top-level variables. I always hear that I need to use state but it is hard to use state when there are many classes/functions. For instance, this is my code:
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { classNames } from "classnames";
import './index.css';
var [a1, b1, c1] = [];
var finished = false;
function Square(props) {
return (
<button className={finished ? (props.valid ? "squares" : "squarez") : 'square'} onClick={() => props.onClick()}>
{props.value}
</button>
);
}
function Board() {
const [arr, setArr] = useState(Array(9).fill(null));
const [xIsNext, setXIsNext] = useState(true);
function handleClick(i) {
if (!arr[i] && !winner) {
const squares = arr.slice();
squares[i] = xIsNext ? 'X' : 'O';
setArr(squares);
setXIsNext(!xIsNext);
}
}
function renderSquare(i) {
return <Square value={arr[i]} onClick={() => handleClick(i)} valid={a1 === i || b1 === i || c1 === i ? true : false} />;
}
const winner = calculateWinner(arr);
const status = winner ? 'Winner is: ' + winner : 'Next player: ' + (xIsNext ? 'X' : 'O');
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{renderSquare(0)}
{renderSquare(1)}
{renderSquare(2)}
</div>
<div className="board-row">
{renderSquare(3)}
{renderSquare(4)}
{renderSquare(5)}
</div>
<div className="board-row">
{renderSquare(6)}
{renderSquare(7)}
{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><button onClick={Board}>alaa </button></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]) {
[a1, b1, c1] = lines[i];
finished = true;
return squares[a];
}
}
return null;
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
It is from React's official website tutorial. So as you can see I have 'finished' and 'a1' 'b1' 'c1' variables at the top. How can I rewrite them with state hooks inside of square class without using top-level variables? For reference, this is the tutorial I am making but I played around with it a little bit to learn: https://reactjs.org/tutorial/tutorial.html
Aucun commentaire:
Enregistrer un commentaire