Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(taro-hooks): add Keyboard hook #54

Merged
merged 10 commits into from
Sep 3, 2023
46 changes: 46 additions & 0 deletions packages/hooks/src/useKeyboard/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
title: useKeyboard
nav:
title: Hooks
path: /hooks
order: 2
group:
title: 小程序
path: /wechat
---

# useKeyboard

获取键盘高度和操作键盘,或获取选取

## 何时使用

需要操作键盘相关内容

## API

```ts
const { height, close, getRange } = useKeyboard();
```

## 参数说明


## 返回值说明

| 参数 | 类型 | 说明 |
| -------- | -------------------------------------------------------- | ------------------ |
| height | `number` | 键盘高度 |
| close | `PromiseWithoutOptionAction<TaroGeneral.CallbackResult>` | 关闭键盘 |
| getRange | `PromiseWithoutOptionAction<TaroGeneral.CallbackResult>` | 获取选择文本的范围 |

## 代码演示

<code src="useKeyboard/index" group="wechat" />

## Hook 支持度

| 微信小程序 | H5 | ReactNative |
| :--------: | :-: | :---------: |
| ✔️ | | |
42 changes: 42 additions & 0 deletions packages/hooks/src/useKeyboard/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useRef, useEffect, useState, useCallback } from '@taro-hooks/core';
import { hideKeyboard } from '@tarojs/taro';
import Taro from '@tarojs/taro';
import usePromise from '../usePromise';

import type { PromiseWithoutOptionAction } from '../type';

export type Close = PromiseWithoutOptionAction<TaroGeneral.CallbackResult>;
export type SelectedRange =
PromiseWithoutOptionAction<TaroGeneral.CallbackResult>;

function useKeyborad() {
const [height, setHeight] = useState<number>(0);

useEffect(() => {
const handle = (e: Taro.onKeyboardHeightChange.CallbackResult) => {
setHeight(e.height);
};

Taro.onKeyboardHeightChange(handle);

return () => {
Taro.offKeyboardHeightChange(handle);
};
});

const handleClose: Close = usePromise<{}, TaroGeneral.CallbackResult>(
hideKeyboard,
);
const getSelectedRange: SelectedRange = usePromise<
{},
TaroGeneral.CallbackResult
>(Taro.getSelectedTextRange);

return {
height,
close: handleClose,
getRange: getSelectedRange,
};
innocces marked this conversation as resolved.
Show resolved Hide resolved
}

export default useKeyborad;
Loading