2016-04-02 23 views
0

Her şeyden önce, const vektör nesnesinin büyük olasılıkla yanlış bir yerde olduğunu sanıyorum ama nereye koyacağımı bilmiyorum. SVG nesnesinin konumunu ok tuşlarıyla denetlemeye çalışıyorum. X'e erişilemiyor gibi görünüyor. Ben hata varReactjs - value undefined

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 

öyle kodu: http://codepen.io/wasteland/pen/GZvWeo?editors=0110

cevap

1

Senin sorunun this.state_handleKey içine tanımlanmamış olmasıdır teşekkür ederiz. Solüsyon bu gibi kurucu içinde this işlevi bağlamak için:

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

Bu genellikle sınıf yöntemleri sınıf örneğini' this erişmesine izin nasıl.

"Hayır Autobinding" üzerinde doküman React: https://facebook.github.io/react/docs/reusable-components.html#no-autobinding

+0

bekleyin, neden 'tanımlanmamış iç' _handleKey' haline this.state' gelir? Bu, 'App' nesnesine bağlı değil mi? –

+1

@AkshatMahajan Hayır, 'bu işlev, ES2015 sınıf sözdizimini kullanırken otomatik olarak App' uygulamasına bağlı değildir. – dannyjolie

+0

Bu konuyla ilgili belgelere işaret edebilir misiniz? MDN sayfalarını inceledim ve aynı şeyi söyleyen bir şey bulamıyorum. Bu davranış hakkında daha fazla bilgi edinmek istiyorum. –