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

问题描述 投票:0回答:1

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

  componentDidMount: function() {
    window.addEventListener('resize', this.handleVisible);
    window.addEventListener('scroll', this.handleVisible);
...
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleVisible);
    window.removeEventListener('scroll', this.handleVisible);
...

  },
javascript reactjs react-component
1个回答
0
投票

您可以创建一个这样的自定义钩子:

export const useResizeScroll = callback => {
  useEffect(() => {
    window.addEventListener('resize scroll', callback);
    return () => window.removeEventListener('resize scroll', callback);
  }, [callback]);
};

然后像这样在您的组件中实现它:

const MyComponent = () => {
  useResizeScroll(handleVisible)

  function handleVisible() { ... }

  return (...)
}
© www.soinside.com 2019 - 2024. All rights reserved.