跳到主要内容

useMotion

监听设备方向

何时使用

当需要监听设备方向时

API

const [
motion,
{
start,
stop,
add,
off,
},
] = useMotion(
autoListen?: boolean,
interval?: interval
);

参数说明

参数说明类型默认值
autoListen是否自动开始监听boolean-
interval执行频率game / ui / normalnormal

返回值说明

返回值说明类型
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

代码演示

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>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️✔️