2017-08-03 39 views
4

我有下面的類片段:訪問event.target內回調反應

constructor(props) { 
    super(props); 

    this.timeout = null; 
} 

search = (e) => { 
    clearTimeout(this.timeout); 
    this.timeout = setTimeout(
     function(){ console.log(e.target); }, 
     500 
    ); 
} 

<input 
    type="text" 
    placeholder="Search by title or author" 
    onKeyPress={this.search} /> 

我不能得到設定的超時值從事件打印的價值,是有什麼,我應該做的,但我不是?

回答

6

SyntheticEvent

作爲每DOC

的SyntheticEvent被合併。這意味着SyntheticEvent對象將被重用,並且在調用 事件回調之後,所有屬性都將被取消。這是出於性能原因。

例子:

function onClick(event) { 
    console.log(event.type); // => "click" 
    const eventType = event.type; // => "click" 

    setTimeout(function() { 
     console.log(event.type); // => null 
     console.log(eventType); // => "click" 
    }, 0);  
} 

如何訪問內回調的價值觀?在一個變量

存儲值:

如果你想在超時回調函數訪問值,則值存儲在一個變量,使用該變量,而不是直接使用的事件對象。

使用event.persist():該事件

如果你想在一個異步的方式來訪問事件屬性,你應該調用event.persist(),這將刪除合成事件從池中,並允許用戶代碼保留對事件的引用。

0

很難說沒有看到你的onKeypress方法,但它可能是一個約束性問題。試着在構造函數中綁定你的搜索。

constructor (props) { 
    super(props); 

    this.timeout = null; 
    this.search = this.search.bind(this); 
} 
+0

香港專業教育學院更新的代碼包括onkeypress事件的方法調用 –

3

試試這個:

search = (e) => { 
e.persist(); 
clearTimeout(this.timeout); 
this.timeout = setTimeout(
    function(){ console.log(e); alert(e) }, 
    500 
); 

}

從你的代碼來看,我認爲你正在使用巴貝爾-插件變換級的屬性。在這種情況下,你不需要構造器部分。

+0

謝謝!成功了! –

0

你打算將timeout作爲狀態嗎?

我的建議是這樣的

constructor(props) { 
    super(props); 
    this.state = { 
     timeout: null 
    } 
} 

search = (e) => { 
    clearTimeout(this.state.timeout); 
    const timeout = setTimeout(
     function(){ console.log(e.target); }, 
     500 
    ); 
    this.setState({timeout: timeout}) 

}