跳到主要内容

useEvent

消息机制

何时使用

当需要全局消息机制时

API

const {
set,
setOnce,
off,
clear,
trigger
} = useEvent(namespace: string);

返回值说明

返回值说明类型
set监听一个或多个事件(eventName: string, ...handlers: Noop[]) => void
setOnce监听一个或多个事件一次(触发后自动移除)(eventName: string, ...handlers: Noop[]) => void
off取消监听一个或多个事件一次(eventName: string, ...handlers: Noop[]) => void
clear取消所有事件监听() => void
trigger触发事件并传入参数(eventName: string, ...params: any[]) => void

代码演示

basic/useEvent/index
import React from 'react';
import { useEvent, useModal } from 'taro-hooks';
import DemoContent from '@src/components/DemoContent';
import { Button } from '@taroify/core';

export default () => {
const show = useModal({ title: 'useEvent', showCancel: false });
const { set, setOnce, off, clear, trigger } = useEvent('useEvent');

const eventName = 'event';
const eventOneceName = 'event-once';

const listener = (params) => {
show({ content: '事件触发成功: ${String(params)}' });
};

return (
<DemoContent>
<Button
className="gap"
block
color="primary"
onClick={() => set(eventName, listener)}
shape="square"
>
设置监听
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => trigger(eventName)}
shape="square"
>
触发监听
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => setOnce(eventOneceName, listener)}
shape="square"
>
设置监听(仅触发一次)
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => trigger(eventOneceName, 'once')}
shape="square"
>
触发监听(仅触发一次)
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => off(eventName)}
shape="square"
>
移除监听
</Button>
<Button
className="gap"
block
color="primary"
onClick={() => clear()}
shape="square"
>
清除所有监听
</Button>
</DemoContent>
);
};

Hook 支持度

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