2017-04-14 90 views
0

react docs事件池是什麼意思?

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

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

// Won't work. this.state.clickEvent will only contain null values. 
this.setState({clickEvent: event}); 

// You can still export event properties. 
this.setState({eventType: event.type}); 
} 

爲什麼event已經是作廢的對象,我們仍然可以得到event.type價值? 是不是指的是event = {type:null}

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

爲什麼​​和eventType = 'click'

你能教我這段代碼的每一行嗎? ...

回答

0
function onClick(event) { 
    console.log(event); // => nullified object. 
    console.log(event.type); // => "click" 

我們可以在處理程序中訪問event的所有屬性。

const eventType = event.type; // => "click" 

我們正在將event.type複製到局部變量中。局部變量不會被取消影響。

setTimeout(function() { 

當處理程序已經返回時,即在事件取消後,函數中的所有內容都將被調用。

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

因此,我們無法訪問event.type,因爲它將被取消。我們將能夠訪問eventType這是一個局部變量,其內容不會受到影響。

// Won't work. this.state.clickEvent will only contain null values. 
    this.setState({clickEvent: event}); 

event是將被取消的事件。保存對狀態的引用不會幫助我們。

// You can still export event properties. 
    this.setState({eventType: event.type}); 
} 

保存event.type是好的。這與將event.type保存到局部變量中相同。在取消之前,我們正在將價值複製到我們的內部狀態。

+0

看起來'console.log(e)'是Asyn,但爲什麼不是'console.log(e.type)'? – Liuuil

+0

事件合併'console.log(event.type)'==='console.log(null.type)'? – Liuuil