如何以可重用的方式在同一组件中添加多个事件侦听器更好?
componentDidMount: function() {
window.addEventListener('resize', this.handleVisible);
window.addEventListener('scroll', this.handleVisible);
...
},
componentWillUnmount: function() {
window.removeEventListener('resize', this.handleVisible);
window.removeEventListener('scroll', this.handleVisible);
...
},
您可以创建一个这样的自定义钩子:
export const useResizeScroll = callback => {
useEffect(() => {
window.addEventListener('resize scroll', callback);
return () => window.removeEventListener('resize scroll', callback);
}, [callback]);
};
然后像这样在您的组件中实现它:
const MyComponent = () => {
useResizeScroll(handleVisible)
function handleVisible() { ... }
return (...)
}