Skip to content
This repository was archived by the owner on Feb 23, 2021. It is now read-only.

Commit 97b027c

Browse files
Remove bind usage + create Escapable component
1 parent becd6af commit 97b027c

File tree

2 files changed

+33
-23
lines changed

2 files changed

+33
-23
lines changed

src/component/escapable.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { Component } from 'react';
2+
import PropTypes from 'prop-types';
3+
4+
class Escapable extends Component {
5+
componentDidMount() {
6+
if (document) {
7+
document.addEventListener('keydown', e => this.handleKeyDown(e));
8+
}
9+
}
10+
11+
componentWillUnmount() {
12+
if (document) {
13+
document.removeEventListener('keydown', e => this.handleKeyDown(e));
14+
}
15+
}
16+
17+
handleKeyDown(event) {
18+
if (event.keyCode === 27) {
19+
this.props.onClose();
20+
}
21+
}
22+
}
23+
24+
Escapable.propTypes = {
25+
onClose: PropTypes.func.isRequired,
26+
};
27+
28+
export default Escapable;

src/component/modal.js

Lines changed: 5 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
import React, { Component } from 'react';
1+
import React from 'react';
22
import { View, ViewPropTypes, StyleSheet } from 'react-native';
33
import PropTypes from 'prop-types';
4-
import { Button } from '../../src/component/button';
4+
import { Button } from './button';
55
import { H4Text } from './text';
66
import Icon from './icon';
7+
import Escapable from './escapable';
78
import { color } from './style';
89

910
const styles = StyleSheet.create({
@@ -34,28 +35,9 @@ const styles = StyleSheet.create({
3435
},
3536
});
3637

37-
class Modal extends Component {
38-
constructor(props) {
39-
props.title = props.title || '';
40-
super(props);
41-
this.handleKeyDown = this.handleKeyDown.bind(this);
42-
}
43-
componentDidMount() {
44-
document.addEventListener('keydown', this.handleKeyDown);
45-
}
46-
47-
componentWillUnmount() {
48-
document.removeEventListener('keydown', this.handleKeyDown);
49-
}
50-
51-
handleKeyDown(event) {
52-
if (event.keyCode === 27) {
53-
this.props.onClose();
54-
}
55-
}
56-
38+
class Modal extends Escapable {
5739
render() {
58-
const { title, style, onClose, children } = this.props;
40+
const { title = '', style, onClose, children } = this.props;
5941
return (
6042
<View style={[styles.modal, style]}>
6143
<H4Text style={styles.title}>{title.toUpperCase()}</H4Text>

0 commit comments

Comments
 (0)