2016-03-19 52 views
4

我得到了用打字機寫的下列組件。 (來自absolutelytyped.org的類型定義)。我得到了綁定到函數的onWheel事件。但是,當它被解僱this是未定義的,所以我應該如何訪問被引用的元素this.div,如果我想/需要改變狀態該怎麼做?reactjs打字稿事件這個undefined

import React = require('react'); 

interface fooProps { 
    src: string; 
} 

class foo extends React.Component<fooProps, {}> 
{ 
    private div: HTMLDivElement; 

    public onWheel(e: React.WheelEvent): void { 
     e.preventDefault(); 
     e.stopPropagation(); 

     //Do stuff with the div, but 'this' is undefined!! 
     this.div; 
    } 
    public render(): JSX.Element { 
       return (
      <div ref={(ref) => this.div = ref} onWheel= { this.onWheel} > 
       <img src={ this.props.src } /> 
       </div >) 
    } 
} 

回答

1

不知道打字稿,但我猜這是同樣的事情,使用類似ES2015語法,這將需要一個構造函數創建組件時一樣,和功能綁定,以便參考此。onWheel工作。

在ES2015

所以,

class foo extends React.Component { 
    constructor(props) { 
    super(props); 
    // Magic happens here: 
    this.onWheel = this.onWheel.bind(this) 
    // Now each instance of foo can use this.onWheel 
    } 

    onWheel() { 
    .... 
    } 

    render(){ 
    .... 
    } 
} 
+2

這實際上是將React組件中的事件處理程序綁定到由Qwertiy回答。如果你像構造函數中的代碼片段一樣進行綁定,那就意味着你只需要創建一個函數的副本,而如果你在'render'方法中做了這個函數,那麼每次React重新渲染的時候函數都會被重新創建組件。當性能是主要考慮因素時,值得注意。 –

+0

但事件是如何發生的?我仍然需要在渲染方法中將onWheel = {this.onWheel}對嗎? – Rutger

+0

只要你已經做到了。它應該工作正常。我的代碼示例沒有'onWheel(e:React.WheelEvent)',因爲關鍵是構造函數中發生了什麼。 – dannyjolie

2
onWheel= { this.onWheel} 
onWheel={this.onWheel.bind(this)} 
+2

你也可以用lambda表單''onWheel = {e => this.onWheel(e)}'將它寫出來,它將使用閉包調用適當的方法 –

1

,如果你不想在構造函數中的每個函數結合的另一種解決方案是使用lambda表達式:

class foo extends React.Component { 
    constructor(props) { 
    super(props); 
    } 

    // The lambda creates a lexical scope so it's autobound 
    onWheel =() => { 
    .... 
    } 

    render() { 
    .... 
    } 
} 

你可以閱讀更多here

+0

打我一拳。 – ThinkingInBits