跳到主要内容

useVisible

获取当前页面是否隐藏或处于后台

何时使用

信息

由于WEB的页面隐藏和小程序的时机不一样. 在WEB端主要是使用document.visibilityState来判断当前的页面状态

当需要根据页面显隐进行判断

API

const visible: boolean = useVisible();

返回值说明

返回值说明类型
visible当前应用是否处于后台boolean

代码演示

basic/useVisible/index
import React from 'react';
import { useEffect, useState } from '@taro-hooks/core';
import { useVisible } from 'taro-hooks';
import { escapeState } from '@taro-hooks/shared';
import DemoContent from '@src/components/DemoContent';
import { View } from '@tarojs/components';
import { Steps } from '@taroify/core';
import { StarOutlined, Star } from '@taroify/icons';

type Item = { timestamp: number; status: boolean };
export default () => {
const visible = useVisible();

const [subscribeList, setSubscribeList] = useState<Item[]>([]);

useEffect(() => {
const currentList = escapeState(subscribeList);
setSubscribeList([
...currentList,
{ timestamp: Date.now(), status: escapeState(visible) },
]);
}, [visible]);

return (
<DemoContent>
<Steps value={subscribeList.length - 1} direction="vertical">
{subscribeList.map(({ timestamp, status }) => (
<Steps.Step
key={timestamp}
icon={status ? <Star /> : <StarOutlined />}
>
<View>{timestamp}</View>
<View>当前状态为: {String(status)}</View>
</Steps.Step>
))}
</Steps>
</DemoContent>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️✔️