こちらのコード index.js を分割してみました。
React のチュートリアル (3目並べの途中まで)
フォルダー構造
$ tree src
src
├── Board.jsx
├── Game.jsx
├── Square.jsx
├── index.css
└── index.js
index.js
// ---------------------------------------------------------------
// index.js
//
// Feb/12/2022
// ---------------------------------------------------------------
import ReactDOM from 'react-dom';
import './index.css';
import Game from './Game.jsx';
// ---------------------------------------------------------------
ReactDOM.render(
<Game />,
document.getElementById('root')
);
// ---------------------------------------------------------------
Game.jsx
// ---------------------------------------------------------------
// Game.jsx
//
// Feb/12/2022
// ---------------------------------------------------------------
import React from 'react';
import Board from './Board.jsx';
// ---------------------------------------------------------------
export default 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>
);
}
}
// ---------------------------------------------------------------
Board.jsx
// ---------------------------------------------------------------
// Board.jsx
//
// Feb/12/2022
// ---------------------------------------------------------------
import React from 'react';
import Square from './Square.jsx';
// ---------------------------------------------------------------
export default class Board extends React.Component {
renderSquare(i) {
return <Square value={i} />;
}
render() {
const status = 'Next player: X';
const width = 3;
const height = 3;
var rows = []
rows.push(status)
rows.push(<p></p>)
for (let it = 0; it < width; it++) {
const cells = [];
for (let jt = 0; jt < height; jt++) {
cells.push(this.renderSquare(it * 3 + jt));
}
rows.push(<div className="board-row">{cells}</div>);
}
return <div>{rows}</div>;
};
}
// ---------------------------------------------------------------
Square.jsx
// ---------------------------------------------------------------
// Square.jsx
//
// Feb/12/2022
// ---------------------------------------------------------------
import React from 'react';
// ---------------------------------------------------------------
export default class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null,
};
}
render() {
return (
<button className="square"
onClick={() => this.setState({value: 'X'})}
>
{this.state.value}
</button>
);
}
}
// ---------------------------------------------------------------
サーバーの起動
npm start