【问题标题】:Reactjs - value undefinedReactjs - 值未定义
【发布时间】:2016-04-02 19:52:07
【问题描述】:

首先,我怀疑 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

谢谢

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您的问题是 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-autobinding

    【讨论】:

    • 等等,为什么this.state 在_handleKey 内部变得未定义? this 不是绑定到 App 对象吗?
    • @AkshatMahajan 不,在使用 ES2015 类语法时,函数内部的this 不会自动绑定到 App this。
    • 您能指出这方面的相关文档吗?我搜索了 MDN 页面,并没有真正找到相同的内容。我想了解更多关于这种行为的信息。
    • @AkshatMahajan 来自 React 文档:facebook.github.io/react/docs/…
    • @Wasteland 如果事件被触发,它会抛出一个错误。但是为了捕获元素上的关键事件,该元素必须具有焦点,例如就像一个带有光标的输入字段。而且我认为在 SVG 元素上没有一些技巧是不可能做到的。
    猜你喜欢
    • 2020-12-05
    • 2016-09-01
    • 2016-05-22
    • 2015-09-21
    • 2021-04-15
    • 2016-05-06
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多