@td-design/rn-hooks
Version:
从ahooks里面抽取的一些在rn项目里可以使用的hooks。提高开发效率
57 lines (54 loc) • 2.08 kB
JavaScript
import { __read } from '../_virtual/_tslib.js';
import { useEffect } from 'react';
import { Keyboard } from 'react-native';
import useBoolean from '../useBoolean/index.js';
import useSafeState from '../useSafeState/index.js';
var emptyCoord = Object.freeze({
screenX: 0,
screenY: 0,
width: 0,
height: 0,
});
var initialValue = {
start: emptyCoord,
end: emptyCoord,
};
function useKeyboard() {
var _a = __read(useBoolean(false), 2), shown = _a[0], _b = _a[1], setTrue = _b.setTrue, setFalse = _b.setFalse;
var _c = __read(useSafeState(initialValue), 2), coords = _c[0], setCoords = _c[1];
var _d = __read(useSafeState(0), 2), keyboardHeight = _d[0], setKeyboardHeight = _d[1];
useEffect(function () {
var subscriptions = [
Keyboard.addListener('keyboardWillShow', function (e) {
setCoords({ start: e.startCoordinates, end: e.endCoordinates });
}),
Keyboard.addListener('keyboardDidShow', function (e) {
setTrue();
setCoords({ start: e.startCoordinates, end: e.endCoordinates });
setKeyboardHeight(e.endCoordinates.height);
}),
Keyboard.addListener('keyboardWillHide', function (e) {
setCoords({ start: e.startCoordinates, end: e.endCoordinates });
}),
Keyboard.addListener('keyboardDidHide', function (e) {
setFalse();
if (e) {
setCoords({ start: e.startCoordinates, end: e.endCoordinates });
}
else {
setCoords(initialValue);
setKeyboardHeight(0);
}
}),
];
return function () {
subscriptions.forEach(function (subscription) { return subscription.remove(); });
};
}, [setCoords, setFalse, setKeyboardHeight, setTrue]);
return {
keyboardShown: shown,
keyboardHeight: keyboardHeight,
coords: coords,
};
}
export { useKeyboard as default };