返回顶部

ahooks——useEventEmitter多个组件之间进行事件通知

参考:

1.ahooks官网:https://ahooks.js.org/zh-CN/hooks/use-event-emitter

useSubscription会在组件创建时自动注册订阅,并在组件销毁时自动取消订阅。

useEventEmitter 适合的是在距离较远的组件之间进行事件通知,或是在多个组件之间共享事件通知。

 

1.父组件:

import { Button } from 'antd'
import { useCallback } from 'react'
import { useEventEmitter } from 'ahooks'
import Child from './child'

export default function Parent() {
  const export$ = useEventEmitter<number>() // 创建事件发射器,number是自定义的参数类型,不设置默认为void

  const handleEmit = useCallback(() => {
    export$.emit(1) // 发射事件
  }, [export$])

  return (
    <>
      <Button onClick={handleEmit}>事件通知</Button>
      <Child export$={export$} />
    </>
  )
}

2.子组件:

import { EventEmitter } from 'ahooks/lib/useEventEmitter'
import { useState } from 'react'

interface IChild {
  export$?: EventEmitter<number>
}

export default function Child(props: IChild) {
  const [num, setNum] = useState<number>()
  const { export$ } = props

  // 订阅事件
  export$?.useSubscription((val: number) => {
    console.log('订阅', val)
    setNum(val)
  })

  return (
    <>
      <h1>{num}</h1>
    </>
  )
}

 

posted @ 2025-05-14 17:16  前端-xyq  阅读(183)  评论(0)    收藏  举报