javascript - ReactJS/Javascript 条件语句

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

谢谢

编辑:

按照下面的建议,我尝试了以下方法,但当您位于四个 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 中的 newXnewY:http://codepen.io/Sphinxxxx/pen/pyWYNG?editors=0010

关于javascript - ReactJS/Javascript 条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36387472/

相关文章:

javascript - innerHTML unencodes < in attributes

javascript 获取唯一键值

svg - 如何确定鼠标事件附近的 SVG 元素?

javascript - 使用 PHP 脚本作为 React 应用程序的 'server'?

javascript - 图像未在 React 中加载

javascript - 如何在 javascript 中将数组中的对象分组为多个数组的 3 个对象集?

javascript - Grunt Watch 反复显示 "Warning: must provide pattern"

javascript - Interactjs 与 SVG

javascript - 是否可以直接使用 jquery 和 Svg(无插件)?

javascript - 当我们已经准备好后端时,为什么我们需要 Express 服务器