跳到主要内容

useTabBar

操作 Tab

何时使用

当需要对 Tab 做一些操作时

API

const { toggleRedDot, toggleBadge, setStyle, setItem, toggle } = useTabBar();

参数说明

返回值说明

参数类型说明
toggle(animation?: boolean) => Promise<General.CallbackResult>显示/隐藏 tabBar
toggleRedDot(index?: number) => Promise<General.CallbackResult>显示/隐藏 tabBar 某项的右上角的红点
toggleBadge(index?: number, text?: string) => Promise<General.CallbackResult>为 tabBar 某项的右上角添加/移除文本(移除时仅需要传递移除index即可)
setItem(option: Omit<ExcludeOption<Taro.setTabBarItem.Option>, 'index'>, index?: number) => Promise<General.CallbackResult>动态设置 tabBar 某项的内容(若不传index则会统一给所有的添加样式)
setStyle(option: ExcludeOption<Taro.setTabBarStyle.Option>) => Promise<General.CallbackResult>动态设置 tabBar 的整体样式

代码演示

layout/useTabBar/index
import React from 'react';
import { useTabBar } from 'taro-hooks';
import Mock from 'mockjs';
import DemoContent from '@src/components/DemoContent';
import { Button } from '@taroify/core';

export default () => {
const { toggleRedDot, toggleBadge, setStyle, setItem, toggle } = useTabBar();

const handleSetStyle = () => {
setStyle({
color: Mock.Random.color(),
selectedColor: Mock.Random.color(),
backgroundColor: Mock.Random.color(),
});
};

const handleSetItem = () => {
setItem({ text: Mock.Random.city() }, Mock.Random.pick([0, 1]));
};

const handleToggleRedDot = () => {
toggleRedDot(Mock.Random.pick([0, 1]));
};

const handleToggleBadge = () => {
toggleBadge(
Mock.Random.pick([0, 1]),
Mock.Random.pick(['serro', undefined]),
);
};

return (
<DemoContent>
<Button
block
color="primary"
className="gap"
onClick={() => toggle()}
shape="square"
>
切换TabBar显示/隐藏
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => toggle(true)}
shape="square"
>
切换TabBar显示/隐藏(动画)
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleToggleRedDot()}
shape="square"
>
随机TabBar 红点 显示/隐藏
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleToggleBadge()}
shape="square"
>
随机TabBar badge 显示/隐藏
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleSetItem()}
shape="square"
>
随机设置TabBar Item
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleSetStyle()}
shape="square"
>
设置TabBar样式
</Button>
</DemoContent>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️✔️✔️