KeyboardEvent
第二次作为
SyntheticBaseEvent
. 这导致回调函数被调用两次。
class App extends Component {
constructor(props) {
super(props)
this.handleKey = this.handleKey.bind(this);
this.myDiv = React.createRef();
}
componentDidMount() {
this.myDiv.current.addEventListener('keydown', this.handleKey);
this.myDiv.current.focus();
}
componentWillUnmount() {
this.myDiv.current.removeEventListener('keydown', this.handleKey);
}
...
handleKey(key){
if (key.key === "A"){
this.callback()
console.log(key)
}
}
render() {
return (
<div className={"App"} tabIndex={"0"} onKeyDown={this.handleKey} ref={this.myDiv}>
</div>
)
}
}