import React, { useState } from "react"; import { Box, Button, Container, Flex, Heading, Input, Stack, Text, Textarea, useToast, } from "@chakra-ui/react"; import { FaEnvelope, FaPhone, FaMapMarkerAlt } from "react-icons/fa"; import { motion } from "framer-motion"; import axios from "axios"; interface ContactInfoProps { icon: React.ReactNode; title: string; content: string; } const ContactInfo = ({ icon, title, content }: ContactInfoProps) => { return ( {icon} {title} {content} ); }; const Contact = () => { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [subject, setSubject] = useState(""); const [message, setMessage] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const [cooldown, setCooldown] = useState(0); const toast = useToast(); const API_URL = process.env.REACT_APP_API_URL || "http://localhost:3001"; // 倒计时函数 React.useEffect(() => { let timer: NodeJS.Timeout | null = null; if (cooldown > 0) { timer = setInterval(() => { setCooldown((prev) => { if (prev <= 1) { if (timer) clearInterval(timer); return 0; } return prev - 1; }); }, 1000); } return () => { if (timer) clearInterval(timer); }; }, [cooldown]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); // 如果在冷却时间内,不允许提交 if (cooldown > 0) { toast({ title: "请求过于频繁", description: `请在${cooldown}秒后再试`, status: "warning", duration: 3000, isClosable: true, position: "top" }); return; } setLoading(true); setError(""); try { // 调用后端API发送邮件 const response = await axios.post(`${API_URL}/api/send-email`, { name, email, subject, message }); // 显示成功消息 toast({ title: "发送成功", description: "消息已发送,感谢您的留言,我会尽快回复您!", status: "success", duration: 5000, isClosable: true, position: "top" }); // 重置表单 setName(""); setEmail(""); setSubject(""); setMessage(""); } catch (err: any) { console.error("发送邮件失败:", err); // 处理速率限制错误 if (err.response?.status === 429) { const remainingTime = err.response.data.remainingTime || 60; setCooldown(remainingTime); toast({ title: "请求过于频繁", description: `请在${remainingTime}秒后再试`, status: "warning", duration: 5000, isClosable: true, position: "top" }); } else { // 显示其他错误消息 setError( err.response?.data?.error || "发送邮件失败,请稍后再试或直接通过电话联系我" ); toast({ title: "发送失败", description: err.response?.data?.error || "发送邮件失败,请稍后再试", status: "error", duration: 5000, isClosable: true, position: "top" }); } } finally { setLoading(false); } }; return ( 联系我 如果您对我的专业技能和项目经验感兴趣,欢迎随时联系我 联系方式 期待与您就Java后台开发和大数据项目进行深入交流,无论是项目合作还是技术讨论,我都非常欢迎。
姓名 * setName(e.target.value)} placeholder="请输入您的姓名" borderColor="gray.300" required /> 邮箱 * setEmail(e.target.value)} placeholder="请输入您的邮箱" borderColor="gray.300" required /> 主题 setSubject(e.target.value)} placeholder="请输入主题" borderColor="gray.300" /> 留言内容 *