我正在使用箭头键移动圆形对象。现在我想将它限制为 svg 区域的高度和宽度。我的条件语句部分起作用,因为一旦球到达任何“墙壁”,它就会卡住并且不会移动到任何地方。我理解它为什么这样做,但想不出一种方法来阻止它这样做。
编辑:CodePen:http://codepen.io/wasteland/pen/GZvWeo?editors=0110
谢谢
class App extends React.Component {
constructor(props) {
super(props)
// Why you need to bind _handleKey:
// https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
this._handleKey = this._handleKey.bind(this)
this.state = {
h: 200,
w: 800,
x: 50,
y: 50,
r: 20,
stroke: "none",
fill: "#6F90A2"
}
}
_currentPosition() {
// Display the current position
console.log(this.state.x, this.state.y);
}
_handleKey(e){
// Define key codes and movement vectors
const vector = {
37: [-1, 0],
38: [0, -1],
39: [1, 0],
40: [0, 1]
};
// Display the current position
this._currentPosition()
// Detect key presses and change the position accordingly
if (e.keyCode in vector) {
if (this.state.x < this.state.w - this.state.r &&
this.state.x > this.state.r &&
this.state.y > this.state.r &&
this.state.y < this.state.h - this.state.r) {
this.setState({
x: this.state.x + vector[e.keyCode][0],
y: this.state.y + vector[e.keyCode][1]
})
}
}
}
componentDidMount() {
document.addEventListener("keydown", this._handleKey, false);
}
render() {
return (
<div>
<Circle { ...this.state } />
</div>
)
}
}
谢谢
编辑:
按照下面的建议,我尝试了以下方法,但当您位于四个 Angular 之一时失败了:
if (e.keyCode in vector) {
if (this.state.x < this.state.w - this.state.r &&
this.state.x > this.state.r &&
this.state.y > this.state.r &&
this.state.y < this.state.h - this.state.r) {
this.setState({
x: this.state.x + vector[e.keyCode][0],
y: this.state.y + vector[e.keyCode][1]
})
} else {
this.setState({
x: this.state.x - vector[e.keyCode][0],
y: this.state.y - vector[e.keyCode][1]
})
}
}
最佳答案
分别处理 x 和 y 坐标。在此处查看 _handleKey
中的 newX
和 newY
:http://codepen.io/Sphinxxxx/pen/pyWYNG?editors=0010
关于javascript - ReactJS/Javascript 条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36387472/