これはReact tutorialの順応です。 私は、1人または2人の選手の選択を使って、自動的に の移動を選択することを目指しています。この段階で何らかの理由で、 がとthis.setState({squares:this.state.squares, xIsNext: !this.state.xIsNext})
ステートメントでキャプチャされていません。 ボタンとスクエアコンポーネントの2つのconsole.log呼び出しからわかります。子コンポーネントに更新された状態が表示されません
これはチュートリアルで使用されている技法なので、正方形配列が の更新ではない理由がわかりません。私は、 状態への変更が全体の状態に反映される前に、 という機能(この場合はhandleMove(i)
、正しい?)が完了していなければならないという、他の投稿とFacebookの不変性の議論を読みました。他のコンポーネントのconsole.logおよびDOM 全体の呼び出しは、四角形のクリックを反映しません。
これはなぜ動作しないのですか?ありがとうございました。
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Tic Tac Toe</title>
<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id='root'></div>
<script type='text/babel' >
function Square(props){
console.log(props.value);
return(
<button className="square" onClick={() => props.onClick()}>{props.value}</button>
);
}
class Board extends React.Component{
renderSquare(i){
console.log(this.props.squares);
return <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />
}
render(){
return(
<div className="board">
<div className="row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component{
constructor(props){
super(props);
this.state = {
onePlayerGame: true,
squares: Array(9).fill(null),
xIsNext: true
}
}
onePlayer(){
this.setState({onePlayerGame: true});
return(
document.getElementById('onePlayer').style.color = "yellow",
document.getElementById('twoPlayer').style.color = "black"
);
}
twoPlayer(){
this.setState({ onePlayerGame: false});
return(
document.getElementById('onePlayer').style.color= "black",
document.getElementById('twoPlayer').style.color= "yellow"
);
}
handleMove(i){
const squares = this.state.squares.slice();
squares[i] = this.state.xIsNext ? 'X':'O';
this.setState({
squares: this.state.squares,
xIsNext: !this.state.xIsNext
})
}
render(){
return(
<div id="main">
<div>
<button className="gameSelect" id="onePlayer" value={this.state.onePlayerGame} onClick={() => this.onePlayer()} >One Player</button>
<button className="gameSelect" id="twoPlayer"value={this.state.onePlayerGame} onClick={() => this.twoPlayer()} >Two Players</button>
</div>
<Board
squares={this.state.squares}
onClick={(i) => this.handleMove(i)} />
</div>
);
}
}
ReactDOM.render(
<Game />,
document.getElementById('root')
)
</script>
</body>
</html>
優秀である必要があります!どうもありがとうございました。 – Cameron