开发者问题收集

ReferenceError:NextJS 项目中未定义 CustomEvent

2020-08-17
2553

我收到错误: ReferenceError:未定义 CustomEvent 。 我知道 CustomEvent 仅在浏览器(客户端)中可用,但我尝试将此函数用作事件:

const mouseEnterHandler =  () => {
  eventDispatcher('cursor', {
    label: 'test',
  })
}

onMouseEnter={mouseEnterHandler()}

export const eventCreator = (name: string, params: Record<string, any>): CustomEvent => {
  const event = new CustomEvent(name, {
    detail: params
  })

  return event
}

export const eventDispatcher = (name: string, params: Record<string, any>): CustomEvent => {
  const event: CustomEvent = eventCreator(name, params)

  document.dispatchEvent(event)

  return event
}
2个回答
export default function SomePage({ props }) {
  useEffect(() => {
    window.addEventListener('test-event', (event) => {
      console.log('test-event', event);
    });

    window.dispatchEvent(new CustomEvent('test-event', { detail: { test: 'testing' } }));
  });

}
Marius Gri
2022-09-20

将其放入 useEffect 钩子中它就会起作用。

guynumerouno
2020-12-03