-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1a3e715
commit e1227f1
Showing
2 changed files
with
61 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,27 @@ | ||
import React from 'react'; | ||
import React, { useState, useEffect, useCallback } from 'react'; | ||
|
||
export const App: React.FC = () => ( | ||
<div className="App"> | ||
<p className="App__message">The last pressed key is [Enter]</p> | ||
</div> | ||
); | ||
export const App: React.FC = () => { | ||
const [keyPress, setKeyPress] = useState<string | null>(null); | ||
|
||
const handleKeyPress = useCallback((event: KeyboardEvent) => { | ||
setKeyPress(event.key); | ||
}, []); | ||
|
||
useEffect(() => { | ||
document.addEventListener('keyup', handleKeyPress); | ||
|
||
return () => { | ||
document.removeEventListener('keyup', handleKeyPress); | ||
}; | ||
}); | ||
|
||
return ( | ||
<div className="App"> | ||
<p className="App__message"> | ||
{keyPress | ||
? `The last pressed key is [${keyPress}]` | ||
: 'Nothing was pressed yet'} | ||
</p> | ||
</div> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import React from 'react'; | ||
|
||
interface State { | ||
keyPress: string | null; | ||
} | ||
|
||
export class App2 extends React.Component<State> { | ||
state: Readonly<State> = { | ||
keyPress: null, | ||
}; | ||
|
||
componentDidMount(): void { | ||
document.addEventListener('keyup', this.handleKeyPress); | ||
} | ||
|
||
componentWillUnmount(): void { | ||
document.removeEventListener('keyup', this.handleKeyPress); | ||
} | ||
|
||
handleKeyPress = (event: KeyboardEvent) => { | ||
this.setState({ keyPress: event.key }); | ||
}; | ||
|
||
render() { | ||
return ( | ||
<div className="App"> | ||
<p className="App__message"> | ||
{this.state.keyPress | ||
? `The last pressed key is [${this.state.keyPress}]` | ||
: 'Nothing was pressed yet'} | ||
</p> | ||
</div> | ||
); | ||
} | ||
} |