useMotion
监听设备方向
何时使用
当需要监听设备方向时
API
const [
motion,
{
start,
stop,
add,
off,
},
] = useMotion(
autoListen?: boolean,
interval?: interval
);
参数说明
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
autoListen | 是否自动开始监听 | boolean | - |
interval | 执行频率 | game / ui / normal | normal |
返回值说明
返回值 | 说明 | 类型 |
---|---|---|
motion | 设备方向信息 | { alpha: number; beta: number; gamma: number; } |
start | 开启监听(若初始未设置autoListen 需在调用addListener 之前调用start ) | (interval?: Interval) => Promise<boolean> |
stop | 停止监听(会清空之前设置的所有监听函数) | (callback) => void |
add | 设置监听函数(可队列设置. 每次设置的都会被队列监听) | (callback: onDeviceMotionChange.Callback) => void |
off | 移除监听函数(移除匹配的监听函数) | (callback) => void |
代码演示
- React
- Vue
device/useMotion/index
import React from 'react';
import { useModal, useMotion } from 'taro-hooks';
import DemoContent from '@src/components/DemoContent';
import { Button, Cell } from '@taroify/core';
export default () => {
const [motion, { start, stop, add, off }] = useMotion(true);
console.log(motion);
const show = useModal({
title: 'useMotion',
showCancel: false,
mask: true,
});
const customListen = (result) => {
show({
content: JSON.stringify(result),
});
off(customListen);
};
const handleListen = async () => {
try {
await add(customListen);
} catch (e) {
show({ content: '监听失败' });
}
};
return (
<DemoContent>
<Button
block
color="primary"
className="gap"
onClick={() => handleListen()}
shape="square"
>
增加一次监听并取消
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => stop()}
shape="square"
>
停止所有
</Button>
<Cell.Group title="方向信息">
{Object.entries(motion).map(([key, value]) => (
<Cell key={key} title={key} brief={JSON.stringify(value)}></Cell>
))}
</Cell.Group>
</DemoContent>
);
};
device/useMotion/index
<template>
<demo-content>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleListen()"
>增加一次监听并取消</nut-button
>
<nut-button shape="square" type="primary" class="gap" block @click="stop()"
>停止所有</nut-button
>
<nut-cell-group title="方向信息">
<nut-cell
v-for="(value, key) in motion"
:key="key"
:title="key"
:sub-title="$filters.stringify(value)"
></nut-cell>
</nut-cell-group>
</demo-content>
</template>
<script setup lang="ts">
import { useModal, useMotion } from 'taro-hooks';
const [motion, { start, stop, add, off }] = useMotion(true);
console.log(motion);
const show = useModal({
title: 'useMotion',
showCancel: false,
mask: true,
});
const customListen = (result) => {
show({
content: JSON.stringify(result),
});
off(customListen);
};
const handleListen = async () => {
try {
await add(customListen);
} catch (e) {
show({ content: '监听失败' });
}
};
</script>
Hook 支持度
微信小程序 | H5 | ReactNative |
---|---|---|
✔️ | ✔️ |