ReactJS / Javascript条件语句

时间:2016-04-03 15:40:33

标签: javascript svg reactjs

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

      }
        } 

1 个答案:

答案 0 :(得分:1)

分别处理x和y坐标。请参阅newX中的newY_handleKeyhttp://codepen.io/Sphinxxxx/pen/pyWYNG?editors=0010