我正在通過React.js構建生命遊戲,並陷入一個不舒服的境地: 我設置爲onClick={ event }
的每個事件都需要點擊2次來執行。React.js事件需要2次點擊才能執行
讓我描述更多: 正如你可以在下面我的代碼看,我有2個按鈕(一個鍵是電路板的尺寸變更爲10×10,另一種是改變的速度間隔)。
一切都很好,除了當我點擊這兩個按鈕時,我需要雙擊執行。在第一次點擊時,通過Chrome中的React Developer Tool,我可以看到包括width, height, speed
在內的狀態已更改,但狀態board
仍保持不變。只有第二次點擊後,board
狀態纔會更改。
任何人都可以解釋爲什麼,並告訴我如何解決?謝謝
這裏是我的代碼
var GameBoard = React.createClass({
getInitialState: function() {
return {
width: 10,
height: 10,
board: [],
speed: 1000,
};
},
// clear the board to the initial state
clear: function(width, height) {
this.setState({
width: width,
height: height,
});
this.setSize();
clearInterval(this.game);
},
// set the size of the board
setSize: function() {
var board = [];
for (var i = 0; i < this.state.height; ++i) {
var line = [];
for (var j = 0; j < this.state.width; ++j)
line.push(0);
board.push(line);
}
this.setState({
board: board
});
},
// start the game
start: function() {
this.game = setInterval(this.gameOfLife, this.state.speed);
},
gameOfLife: function() { // game of life },
// change the speed of the game
changeSpeed: function(speed) {
this.setState({ speed: speed });
clearInterval(this.game);
this.start();
},
// change the size to 10 x 10
smallSize: function() {
this.clear(10, 10);
},
render: function() {
return (
<div className="game-board">
<h1>Conway's Game of Life</h1>
<h2>Generation: { this.state.generation }</h2>
<div className="control">
<button className="btn btn-default" onClick={ this.start }>Start</button>
</div>
<Environment board={ this.state.board } onChangeSquare = { this.onChangeSquare }/>
<div className="size">
<h2>Size</h2>
<button className="btn btn-default" onClick={ this.smallSize }>Small (10 x 10)</button>
</div>
<div className="speed">
<h2>Speed</h2>
<button className="btn btn-default" onClick={ this.changeSpeed.bind(this, 900) }>Slow</button>
</div>
</div>
)
}
});
嗯,不確定。但是,你不需要在'onClick'處理程序中'綁定'使用'this'的所有函數嗎?例如'smallSize' –
通過'smallSize'使用'bind'是什麼意思?我認爲這種方法很好,只是'onClick'的效果不起作用。 – pexea12
即使第二個函數似乎在其實現中使用了this,this.clear.bind(this)'this.smallSize.bind(this)'''this.clear(10,10) ')。它不應該導致你所看到的問題,但它對我來說似乎有點奇怪 –