Reactjs-值未定义

Reactjs - value undefined

本文关键字:未定义 Reactjs-      更新时间:2023-11-28

首先,我怀疑const vector对象可能放错了地方,但我不知道该放在哪里。我试图用箭头键控制SVG对象的位置。它似乎无法访问x.

class Circle extends React.Component {
  render() {
    const { h, w, x, y, r, stroke, fill } = this.props;
    return (
      <svg height={h} width={w}>
        <circle cx={x} cy={y} r={r}
          stroke={stroke} strokeWidth="3" fill={fill} 
        />
      </svg> 
    )
  }
}
class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      h: 100,
      w: 500,
      x: 50,
      y: 50,
      r: 40,
      stroke: "black",
      fill: "red"
    }
  }
  _currentPosition() {
    // Display the current position
    console.log(this.state.x, this.state.y);
  }
  _handleKey(e){
    // Define key codes and movement vectors
    const vector = {
        37: [-10, 0],
        38: [0, -10],
        39: [10, 0],
        40: [0, 10]
    };
    // Display the current position
    this.currentPosition;
    // Detect key presses and change the position accordingly
      if (e.keyCode in vector) {
      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 } onKeyPress={this.handleKeyPress}/>
      </div>
    )
  }
}
ReactDOM.render(<App />, document.getElementById('app'))

我得到了错误:

VM211 pen.js:76Uncaught TypeError: Cannot read property 'x' of undefined
_handleKey @ VM211 pen.js:76

代码是:http://codepen.io/wasteland/pen/GZvWeo?editors=0110

感谢

您的问题是this.state_handleKey内部未定义。解决方案是将函数绑定到构造函数中的this,如下所示:

constructor(props) {
  super(props)
  this._handleKey = this._handleKey.bind(this)
  ...
  ...

这通常是允许类方法访问类实例"this"的方式。

关于"无自动绑定"的React文档:https://facebook.github.io/react/docs/reusable-components.html#no-自动绑定