RMO-Front/src/components/CookieConsent.tsx

79 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import './CookieConsent.css'
function CookieConsent() {
const [showConsent, setShowConsent] = useState(false)
useEffect(() => {
// 检查用户是否已经做出过选择
try {
const consent = localStorage.getItem('cookieConsent')
console.log('[CookieConsent] Checking localStorage, consent =', consent)
if (!consent) {
console.log('[CookieConsent] No consent found, will show after delay')
// 延迟显示,让页面先加载完成
const timer = setTimeout(() => {
console.log('[CookieConsent] Setting showConsent to true')
setShowConsent(true)
}, 1000) // 减少延迟时间到1秒
return () => {
console.log('[CookieConsent] Cleaning up timer')
clearTimeout(timer)
}
} else {
console.log('[CookieConsent] Consent already given, not showing. To test, clear localStorage: localStorage.removeItem("cookieConsent")')
}
} catch (error) {
console.error('[CookieConsent] Error accessing localStorage:', error)
// 如果localStorage不可用仍然显示
const timer = setTimeout(() => {
setShowConsent(true)
}, 1000)
return () => clearTimeout(timer)
}
}, [])
const handleAccept = () => {
console.log('CookieConsent: User accepted')
localStorage.setItem('cookieConsent', 'accepted')
setShowConsent(false)
}
const handleReject = () => {
console.log('CookieConsent: User rejected')
localStorage.setItem('cookieConsent', 'rejected')
setShowConsent(false)
}
console.log('CookieConsent: Rendering, showConsent =', showConsent)
if (!showConsent) {
return null
}
return (
<div className="cookie-consent-overlay">
<div className="cookie-consent">
<div className="cookie-consent-content">
<h3 className="cookie-consent-title">Cookies</h3>
<p className="cookie-consent-text">
使 Cookies 使 Cookies 使 Cookies 使 Cookies <Link to="/privacy-policy" className="cookie-link">Cookies </Link>
</p>
</div>
<div className="cookie-consent-actions">
<button onClick={handleReject} className="cookie-btn cookie-btn-reject">
</button>
<button onClick={handleAccept} className="cookie-btn cookie-btn-accept">
</button>
</div>
</div>
</div>
)
}
export default CookieConsent