pet*_*gan 0 javascript setinterval reactjs
我正在尝试编写一个小蛇游戏,但在改变蛇的方向时遇到了麻烦。我在下面包含了整个组件。
我看到以下错误:
this.setState is not a function
这是在changeDirection方法中引起的。
请参阅下面的完整代码:
export default class Example extends Component {
constructor(props){
super(props);
this.state = {
snakeLeftPos: 0,
snakeDirection: 'right',
boardWidth: 20,
boardHeight: 20
};
}
componentDidMount() {
document.onkeydown = this.changeDirection;
setInterval(() => {
this.moveSnake();
}, 1000);
}
moveSnake() {
const { boardWidth, snakeDirection} = this.state;
if(snakeDirection === 'right') {
this.setState((prevState) => {
return snakeDirection: prevState.snakeDirection + 20
});
}
//same logic for other directions
}
changeDirection(e) {
switch(e.keyCode) {
case 37:
this.setState(() => {
return {
snakeDirection: 'left'
}
});
break;
//other switch cases omitted for right, up, down
}
}
render() {
const { snakeLeftPos, boardHeight, boardWidth } = this.state;
return(
<div>
<Snake snakeLeftPos={snakeLeftPos} />
<Board boardHeight={boardHeight} boardWidth={boardWidth}/>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
这不是绑定到类函数,你必须在构造函数中手动完成,
尝试这个 :
constructor(props){
super(props);
this.state = {
snakeLeftPos: 0,
snakeDirection: 'right',
boardWidth: 20,
boardHeight: 20
};
this.moveSnake = this.moveSnake.bind(this);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1236 次 |
| 最近记录: |