<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function Square(props){
return (
<button className="square" onClick={()=>props.onClick()}>
{props.value}
</button>
);
}
class Board extends React.Component{
constructor(){
super();
this.state = {
squares:Array(9).fill('#'),
xIsNext:true
};
}
restart(){
// this.state.squares.fill('#');
const squares = this.state.squares.slice();
for(let i = 0;i < this.state.squares.length;i++){
squares[i] = '#';
}
this.setState({
squares:squares,
});
}
renderSquare(i){
return <Square value={this.state.squares[i]} onClick={()=>this.handleClick(i)}/>;
}
renderSquareRs(){
return <Square value=' restart ' onClick={()=>this.restart()}/>;
}
handleClick(i){
const squares = this.state.squares.slice();
if(squares[i]=='#'){
squares[i] = this.state.xIsNext?'X':'0';
this.setState({
squares:squares,
xIsNext:!this.state.xIsNext
});
}
}
calculateWinner(squares){
const lines = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[2,4,6],
[0,4,8]
];
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;
}
render(){
let status;
const winner = this.calculateWinner(this.state.squares);
if(winner&&winner!="#"){
status = "Winner:" + winner;
}else
status = "Next player:" + (this.state.xIsNext?'X':'0');
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 className="board-row">
{this.renderSquareRs()}
</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>
<div>{/* TODO */}</div>
</div>
</div>
)
}
}
ReactDOM.render(
<Game/>,
document.getElementById('root')
)
</script>
</body>
</html>
来自视频教程,自己学习理解