2016-04-02 13 views
0

まず、constベクトルオブジェクトはおそらく間違った場所にあると思われますが、どこに置くべきかわかりません。 私は、矢印キーでSVGオブジェクトの位置を制御しようとしています。それはxにアクセスすることができないようです。私はエラーを持っているReactjs - 値は定義されていません

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

答えて

1

あなたの問題はthis.state_handleKey内部で定義されていないということです、ありがとうございました。ソリューションは、このようなあなたのコンストラクタ内thisに関数をバインドすることです:

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

これはクラスメソッドは、クラスのインスタンスのthisにアクセスすることを可能にする方法が一般的です。

は "いいえ自動バインド" にドキュメントに反応: `` _handleKey`内不定となりthis.state`ない理由https://facebook.github.io/react/docs/reusable-components.html#no-autobinding

+0

待ちを、? 'this'は' App'オブジェクトにバインドされていませんか? –

+1

@AkshatMahajanいいえ、関数内の 'this'は、ES2015クラス構文を使用しているとき、自動的にアプリケーション' this'にバインドされません。 – dannyjolie

+0

これに関する関連ドキュメントを参照できますか?私はMDNのページを精査して、同じことを実際に見つけることはできません。私はこの動作についてもっと知りたいと思います。 –

関連する問題