猿问

如何为同一个 React 组件添加多个事件监听器?

以更可重用的方式在同一个组件中添加多个事件侦听器会更好吗?


  componentDidMount: function() {

    window.addEventListener('resize', this.handleVisible);

    window.addEventListener('scroll', this.handleVisible);

...

  },


  componentWillUnmount: function() {

    window.removeEventListener('resize', this.handleVisible);

    window.removeEventListener('scroll', this.handleVisible);

...


  },



牧羊人nacy
浏览 228回答 2
2回答

慕姐8265434

你可以像这样创建一个自定义钩子:import { useEffect } from 'react'export const useResizeScroll = callback => {&nbsp; useEffect(() => {&nbsp; &nbsp; window.addEventListener('resize scroll', callback);&nbsp; &nbsp; return () => window.removeEventListener('resize scroll', callback);&nbsp; }, [callback]);};然后在你的组件中实现它,如下所示:const MyComponent = () => {&nbsp; useResizeScroll(handleVisible)&nbsp; function handleVisible() { ... }&nbsp; return (...)}笔记:这将要求您转到组件的钩子实现。所以如果你在使用this.state = { ... },你需要去学习如何使用 React 的useState钩子:React useState Hook更新:如果您希望挂钩更灵活,例如选择您希望组件挂钩的事件侦听器,那么您可以这样做:export const useResizeScroll = (eventListener, callback) => {&nbsp; useEffect(() => {&nbsp; &nbsp; window.addEventListener(eventListener, callback);&nbsp; &nbsp; return () => window.removeEventListener(eventListener, callback);&nbsp; }, [callback]);};然后像这样实现它:useResizeScroll('resize scroll', handleVisible)更高级的用例:您还可以通过使用 React Context 来改进您的自定义钩子。这是一个实现跟踪窗口宽度的钩子的示例。import React, { createContext, useContent, useEffect, useState } from 'react'const ViewportContext = createContext({ width: window.innerWidth })export const ViewportProvider = ({ children }) => {&nbsp; const [width, setWidth] = useState(window.innerWidth)&nbsp; function handleResize() {&nbsp; &nbsp; setWidth(window.innerWidth)&nbsp; }&nbsp; useEffect(() => {&nbsp; &nbsp; window.addEventListener('resize', handleResize)&nbsp; &nbsp; return () => window.removeEventListener('resize', handleResize)&nbsp; }, [])&nbsp; return (&nbsp; &nbsp; <ViewportContext.Provider value={{ width }}>&nbsp; &nbsp; &nbsp; {children}&nbsp; &nbsp; </ViewportContext.Provider>&nbsp; )}export const useViewport = () => {&nbsp; const { width } = useContext(ViewportContext)&nbsp; return { width }}然后您可以在任何组件中使用它,如下所示:const { width } = useViewport()这应该为您提供足够的信息来构建自定义挂钩以匹配您的用例。

LEATH

这个 :window.addEventListener('resize&nbsp;scroll',&nbsp;callback);对我不起作用。我不得不这样做:window.addEventListener('resize',&nbsp;callback); window.addEventListener('scroll',&nbsp;callback);但这有效:window.removeEventListener('resize&nbsp;scroll',&nbsp;handleResize)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答