-
Notifications
You must be signed in to change notification settings - Fork 24k
/
KeyboardExample.js
113 lines (100 loc) · 2.75 KB
/
KeyboardExample.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
import type {
RNTesterModule,
RNTesterModuleExample,
} from '../../types/RNTesterTypes';
import type {KeyboardEvent} from 'react-native/Libraries/Components/Keyboard/Keyboard';
import * as React from 'react';
import {useEffect, useState} from 'react';
import {Keyboard, StyleSheet, Text, View} from 'react-native';
type KeyboardEventViewerProps = {
showEvent: 'keyboardWillShow' | 'keyboardDidShow',
hideEvent: 'keyboardWillHide' | 'keyboardDidHide',
};
const KeyboardEventViewer = (props: KeyboardEventViewerProps): React.Node => {
const {showEvent, hideEvent} = props;
const [isShown, setIsShown] = useState(false);
const [lastEvent, setLastEvent] = useState<?KeyboardEvent>();
useEffect(() => {
const subscription = Keyboard.addListener(showEvent, ev => {
setIsShown(true);
setLastEvent(ev);
});
return () => subscription.remove();
}, [showEvent]);
useEffect(() => {
const subscription = Keyboard.addListener(hideEvent, ev => {
setIsShown(false);
setLastEvent(ev);
});
return () => subscription.remove();
}, [hideEvent]);
return (
<View>
<Text>
<Text>Keyboard is </Text>
{isShown ? (
<Text style={styles.openText}>open</Text>
) : (
<Text style={styles.closeText}>closed</Text>
)}
</Text>
<View style={styles.eventBox}>
<Text>
{lastEvent
? JSON.stringify(lastEvent, null, 2)
: 'No events observed'}
</Text>
</View>
</View>
);
};
const keyboardWillShowHideExample: RNTesterModuleExample = {
title: 'keyboardWillShow / keyboardWillHide',
platform: 'ios',
render: () => (
<KeyboardEventViewer
showEvent="keyboardWillShow"
hideEvent="keyboardWillHide"
/>
),
};
const keyboardDidShowHideExample: RNTesterModuleExample = {
title: 'keyboardDidShow / keyboardDidHide',
render: () => (
<KeyboardEventViewer
showEvent="keyboardDidShow"
hideEvent="keyboardDidHide"
/>
),
};
const styles = StyleSheet.create({
closeText: {
color: 'red',
},
openText: {
color: 'green',
},
eventBox: {
marginTop: 10,
padding: 5,
borderWidth: StyleSheet.hairlineWidth,
},
});
const KeyboardExample: RNTesterModule = {
title: 'Keyboard',
description: 'Demonstrates usage of the "Keyboard" static API',
documentationURL: 'https://reactnative.dev/docs/keyboard',
category: 'Basic',
examples: [keyboardWillShowHideExample, keyboardDidShowHideExample],
};
export default KeyboardExample;