栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

reactjs事件侦听器beforeunload添加但未删除

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

reactjs事件侦听器beforeunload添加但未删除

removeEventListener
应该得到的引用到在分配相同的回调
addEventListener
。重新创建该功能将无效。解决方案是在其他地方(
onUnload
在本示例中)创建回调,并将其作为对
addEventListener
和的引用传递
removeEventListener

import React, { PropTypes, Component } from 'react';class MyComponent extends Component {    onUnload = e => { // the method that will be used for both add and remove event       e.preventDefault();       e.returnValue = '';    }    componentDidMount() {       window.addEventListener("beforeunload", this.onUnload);    }    componentWillUnmount() {        window.removeEventListener("beforeunload", this.onUnload);    }    render() {        return ( <div>     Some content </div>        );    }}export default MyComponent

反应钩子

您可以

beforeunload
使用
useRef
useEffect
钩子将事件处理抽象为自定义钩子。

自定义钩子

useUnload
接收一个函数(
fn
)并将其分配给当前引用。它会调用
useEffect
,并设置事件处理程序,并在删除组件时返回清除函数以删除事件处理程序。

import { useRef, useEffect } from 'react';const useUnload = fn => {  const cb = useRef(fn);  useEffect(() => {    const onUnload = cb.current;    window.addEventListener("beforeunload", onUnload);    return () => window.removeEventListener("beforeunload", onUnload);  }, [cb]);};export default useUnload;

用法:

const MyComponent = () => {  useUnload(e => {    e.preventDefault();    e.returnValue = '';  });  return (    <div>      Some content    </div>  );};


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380408.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号