useVisible
获取当前页面是否隐藏或处于后台
何时使用
信息
由于WEB的页面隐藏和小程序的时机不一样. 在WEB端主要是使用document.visibilityState来判断当前的页面状态
当需要根据页面显隐进行判断
API
const visible: boolean = useVisible();
返回值说明
返回值 | 说明 | 类型 |
---|---|---|
visible | 当前应用是否处于后台 | boolean |
代码演示
- React
- Vue
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>
);
};
basic/useVisible/index
<template>
<demo-content>
<nut-steps direction="vertical" :current="subscribeList.length">
<nut-step
v-for="{ timestamp, status } in subscribeList"
:key="timestamp"
:title="timestamp + ''"
:content="'当前状态为:' + status"
:icon="status ? 'star-fill-n' : 'star-n'"
></nut-step>
</nut-steps>
</demo-content>
</template>
<script setup lang="ts">
import { useEffect, useState } from '@taro-hooks/core';
import { useVisible } from 'taro-hooks';
import { escapeState } from '@taro-hooks/shared';
const visible = useVisible();
type Item = { timestamp: number; status: boolean };
const [subscribeList, setSubscribeList] = useState<Item[]>([]);
useEffect(() => {
const currentList = escapeState(subscribeList);
setSubscribeList([
...currentList,
{ timestamp: Date.now(), status: escapeState(visible) },
]);
}, [visible]);
</script>
Hook 支持度
微信小程序 | H5 | ReactNative |
---|---|---|
✔️ | ✔️ |