2017-08-03 35 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}) 

}