简体   繁体   English

ReactJS / Javascript条件语句

[英]ReactJS / Javascript conditional statements

I am using arrow keys to move the circle object. 我正在使用箭头键移动圆形对象。 Now I want to limit it to the height and witdth of the svg area. 现在我想将它限制在svg区域的高度和高度。 My conditional statements partially work as once the ball gets to any of the 'walls' it gets stuck and does not move anywhere. 我的条件陈述部分起作用,因为一旦球到达任何“墙壁”,它就会卡住并且不会移动到任何地方。 I understand why it does it but can't think of a way to prevent it from doing it. 我明白为什么会这样做,但却想不出办法阻止它这样做。

Edit: CodePen: http://codepen.io/wasteland/pen/GZvWeo?editors=0110 编辑:CodePen: http ://codepen.io/wasteland/pen/GZvWeo?edit = 0110

Thanks 谢谢

 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> ) } } 

Thank you 谢谢

Edit: 编辑:

Following a suggestion below, I tried the following, which fails when you're in one of the four corners: 根据下面的建议,我尝试了以下操作,当您处于四个角落中的一个时,它会失败:

 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]  
        })

      }
        } 

Handle the x and y coordinates separately. 分别处理x和y坐标。 See newX and newY in _handleKey here: http://codepen.io/Sphinxxxx/pen/pyWYNG?editors=0010 在这里查看newXnewYhttpnewY _handleKey

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM