我正在使用React.js构建生命游戏,但遇到了一个棘手的问题:
我设置了每个事件为
让我进一步描述一下: 如下所示,我有两个按钮(一个按钮是用于将板子的大小更改为10 x 10,另一个按钮是用于更改间隔速度)。
一切都很好,除了当我单击这两个按钮时,我需要双击才能执行。在第一次单击时,通过Chrome中的React Developer Tool,我可以看到包括
有人能解释一下为什么吗,并告诉我如何解决?谢谢
以下是我的部分代码:
onClick={ event }
,但需要点击两次才能执行。让我进一步描述一下: 如下所示,我有两个按钮(一个按钮是用于将板子的大小更改为10 x 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>
)
}
});
bind
和smallSize
是什么意思?我认为这个方法很好,只是onClick
的效果没有起作用。 - pexea12this.clear.bind(this)
但没有this.smallSize.bind(this)
- 即使第二个函数似乎在实现中使用了this
(this.clear(10,10)
)。这不应该导致你看到的问题,但它似乎有点奇怪。 - Ashley Coolmanthis
。因此,在这里我们不需要使用.bind(this)
。 - pexea12this.setState
调用中设置宽度、高度和板块。 - ZekeDroid