You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React Hooks实现页面初始化后延迟弹出广告式模态框

实现页面加载后自动弹出的广告模态框(React Hooks版)

要实现页面初始化完成后延迟自动弹出模态框,只需借助React的useEffect钩子设置定时器,在组件挂载后触发打开逻辑,同时做好定时器清理避免内存泄漏。以下是修改后的完整代码:

import React from 'react';
import Button from '@mui/material/Button';
import Modal from '@mui/material/Modal';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';

// 自定义模态框样式,可按需调整
const style = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: 400,
  bgcolor: 'background.paper',
  border: '2px solid #000',
  boxShadow: 24,
  p: 4,
};

export default function AutoPopupModal() {
  const [open, setOpen] = React.useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  // 组件挂载后触发延迟弹出逻辑
  React.useEffect(() => {
    // 延迟3秒弹出,可修改毫秒数调整等待时间
    const timer = setTimeout(handleOpen, 3000);
    
    // 组件卸载时清理定时器,防止内存泄漏
    return () => clearTimeout(timer);
  }, []); // 空依赖数组确保仅在组件挂载时执行一次

  return (
    <div>
      {/* 不需要手动触发按钮的话,直接删除这一行即可 */}
      <Button onClick={handleOpen}>手动打开模态框</Button>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box sx={style}>
          <Typography id="modal-modal-title" variant="h6" component="h2">
            限时特惠通知
          </Typography>
          <Typography id="modal-modal-description" sx={{ mt: 2 }}>
            全场商品8折起,活动仅限3天,点击立即参与!
          </Typography>
          {/* 可添加广告相关操作按钮 */}
          <Button onClick={handleClose} sx={{ mt: 2, mr: 1 }}>
            关闭
          </Button>
          <Button variant="contained" sx={{ mt: 2 }}>
            查看详情
          </Button>
        </Box>
      </Modal>
    </div>
  );
}

实用优化建议

  • 避免重复弹出:不想用户每次刷新都看到弹窗的话,用localStorage记录弹出状态:
    React.useEffect(() => {
      const hasShown = localStorage.getItem('adModalShown');
      if (!hasShown) {
        const timer = setTimeout(() => {
          handleOpen();
          localStorage.setItem('adModalShown', 'true');
        }, 3000);
        return () => clearTimeout(timer);
      }
    }, []);
    
  • 自动关闭功能:需要弹窗自动关闭的话,在打开时新增定时器:
    const handleOpen = () => {
      setOpen(true);
      // 5秒后自动关闭弹窗
      setTimeout(handleClose, 5000);
    };
    
  • 移动端适配:修改style中的宽度设置,用width: '90%'和maxWidth: 400适配小屏幕。

内容的提问来源于stack exchange,提问作者lekshmi priya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 06:15:13