2017-09-19 239 views
-1

我试图删除事件侦听器,但因为removeEventListener预计类型EventListenerOrEventListenerObject但此事件处理程序的类型,我得到的打字稿错误是FormEvent的:打字稿错误

private saveHighScore (event: React.FormEvent<HTMLInputElement>) { 

这是所如何除去事件:

window.removeEventListener('click', this.saveHighScore); 

错误消息:

TS2345: Argument of type '(event: FormEvent<HTMLInputElement>) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'. Type '(event: FormEvent<HTMLInputElement>) => void' is not assignable to type 'EventListenerObject'. Property 'handleEvent' is missing in type '(event: FormEvent<HTMLInputElement>) => void'.

那么这将是除去反应FormEvent正确的方法是什么?

更新: 我加入这个事件是这样的:

<input onClick={this.saveHighScore} className="btn btn--high-score" type="submit" value="Save"/> 
+0

您是否已经使用'window.addEventListener'?如果是这样,怎么样? –

+0

随着输入元件上的的onClick(参见后更新)。 – Floris

+0

'的onClick = {this.saveHighScore}'使用阵营的内部事件处理;它完全独立于实际的DOM事件监听器处理。 –

回答

1

的处理程序管理的反应,所以保持管理存在。如果添加侦听器应该是有条件的,那么在render方法中进行管理。类似以下内容:

saveHighScore =() => { 
    this.setState({ 
    scoreSaved: true, 
    }); 
} 

render() { 
    const onClickHandler = this.state.scoreSaved ? null : this.saveHighScore; 
    return (
    <input onClick={onClickHandler} className="btn btn--high-score" type="submit" value="Save"/> 
); 
}