跳到主要内容

UI Hooks

UI 相关的 Hooks 集合。

useTheme

主题管理 Hook。

import { useTheme } from 'taro-uno';

function Demo() {
const { theme, setTheme, toggleTheme } = useTheme();

return (
<div>
<p>当前主题: {theme}</p>
<button onClick={toggleTheme}>切换主题</button>
<button onClick={() => setTheme('dark')}>深色模式</button>
<button onClick={() => setTheme('light')}>浅色模式</button>
</div>
);
}

返回值

参数说明类型
theme当前主题'light' | 'dark'
setTheme设置主题(theme: 'light' | 'dark') => void
toggleTheme切换主题() => void

useStyle

动态样式管理 Hook。

import { useStyle } from 'taro-uno';

function Demo() {
const { style, setStyle, mergeStyle } = useStyle({
color: 'red',
fontSize: 14,
});

return (
<div style={style}>
<button onClick={() => mergeStyle({ color: 'blue' })}>
改变颜色
</button>
</div>
);
}

usePlatform

平台检测 Hook。

import { usePlatform } from 'taro-uno';

function Demo() {
const { platform, isWeapp, isH5, isRN } = usePlatform();

return (
<div>
<p>当前平台: {platform}</p>
{isWeapp && <p>微信小程序环境</p>}
{isH5 && <p>H5 环境</p>}
{isRN && <p>React Native 环境</p>}
</div>
);
}

返回值

参数说明类型
platform当前平台'weapp' | 'h5' | 'rn' | 'harmony'
isWeapp是否微信小程序boolean
isH5是否 H5boolean
isRN是否 React Nativeboolean
isHarmony是否鸿蒙boolean

useResponsive

响应式布局 Hook。

import { useResponsive } from 'taro-uno';

function Demo() {
const { breakpoint, isMobile, isTablet, isDesktop } = useResponsive();

return (
<div>
<p>当前断点: {breakpoint}</p>
{isMobile && <MobileLayout />}
{isTablet && <TabletLayout />}
{isDesktop && <DesktopLayout />}
</div>
);
}

返回值

参数说明类型
breakpoint当前断点'xs' | 'sm' | 'md' | 'lg' | 'xl'
isMobile是否移动端boolean
isTablet是否平板boolean
isDesktop是否桌面端boolean

useMediaQuery

媒体查询 Hook。

import { useMediaQuery } from 'taro-uno';

function Demo() {
const isLargeScreen = useMediaQuery('(min-width: 1024px)');
const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');

return (
<div>
{isLargeScreen ? '大屏幕' : '小屏幕'}
{prefersDark && '用户偏好深色模式'}
</div>
);
}

useVirtualScroll

虚拟滚动 Hook。

import { useVirtualScroll } from 'taro-uno';

function Demo() {
const data = Array.from({ length: 10000 }, (_, i) => ({ id: i }));

const { virtualItems, totalHeight, containerRef } = useVirtualScroll({
data,
itemHeight: 50,
overscan: 5,
});

return (
<div ref={containerRef} style={{ height: 400, overflow: 'auto' }}>
<div style={{ height: totalHeight, position: 'relative' }}>
{virtualItems.map(({ item, index, style }) => (
<div key={item.id} style={style}>
项目 {index}
</div>
))}
</div>
</div>
);
}