React倒计时组件:剩余30分钟时如何切换背景/文字为绿色?
No problem at all! Let's tweak your React countdown component to switch the text (or background) color to green when there's 30 minutes or less left on the clock. Here's how to make it work:
Step 1: Calculate Total Remaining Minutes
First, we need to compute the total remaining minutes (combining days, hours, and current minutes) to accurately check if we're within the 30-minute window. This ensures we don't miss edge cases like "0 days, 0 hours, 29 minutes" or even "0 days, 0 hours, 30 minutes".
Step 2: Add Conditional Styling
We'll use inline styles (or CSS classes if you prefer) to dynamically change the color based on our 30-minute threshold.
Here's the modified code with these updates:
import React, { useState, useEffect } from 'react'; function Counter() { const TimeLeft = () => { const countDownDate = new Date("Dec 23, 2020 15:37:25").getTime(); const now = new Date().getTime(); let distance = countDownDate - now; // Handle countdown end to avoid negative numbers if (distance < 0) { return { days: 0, hours: 0, minutes: 0, seconds: 0 }; } const timeLeft = { days: Math.floor(distance / (1000 * 60 * 60 * 24)), hours: Math.floor((distance / (1000 * 60 * 60)) % 24), minutes: Math.floor((distance / 1000 / 60) % 60), seconds: Math.floor((distance / 1000) % 60) }; return timeLeft; }; const [timeLeft, setTimeLeft] = useState(TimeLeft()); useEffect(() => { const timer = setTimeout(() => { setTimeLeft(TimeLeft()); }, 1000); return () => clearTimeout(timer); }); // Calculate total remaining minutes to check the 30-minute threshold const totalRemainingMinutes = timeLeft.days * 24 * 60 + timeLeft.hours * 60 + timeLeft.minutes; const isTimeAlmostUp = totalRemainingMinutes <= 30; return ( <div> <h1>Hurry</h1> {/* Conditionally set text color to green when 30 mins or less remain */} <h3 style={{ color: isTimeAlmostUp ? 'green' : 'inherit' }}> {timeLeft.days} Days {timeLeft.hours} Hours {timeLeft.minutes} Minutes {timeLeft.seconds} Seconds </h3> </div> ); } export default Counter;
Key Changes Breakdown:
- Total Minutes Calculation:
totalRemainingMinutesconverts all remaining time into a single minute value, so we can reliably check if we're at or below the 30-minute mark. - Conditional Styling: The
<h3>uses a ternary operator in itsstyleprop to switch text color to green whenisTimeAlmostUpis true, otherwise it uses the default inherited color. - Countdown End Handling: Added a check for when
distance < 0(countdown finished) to prevent negative numbers from displaying.
If you'd rather change the background color instead, adjust the style prop to target backgroundColor (you might also want to change text color for readability):
<h3 style={{ backgroundColor: isTimeAlmostUp ? 'green' : 'transparent', color: isTimeAlmostUp ? 'white' : 'inherit' }}>
That's all! Your countdown will now visually alert users when there's only 30 minutes left on the clock.
内容的提问来源于stack exchange,提问作者aish

