ReactJS / Javascript条件语句

荒地

我正在使用箭头键移动圆形对象。现在,我想将其限制为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>
    )
  }
}

谢谢

编辑:

根据以下建议,我尝试了以下操作,但当您处于四个角落之一时,该操作将失败:

 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坐标。newXnewY_handleKey这里:http://codepen.io/Sphinxxxx/pen/pyWYNG?editors=0010

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章