“心情♥追踪器”卡片组件
1.先看效果
2.源代码
import React, { useState } from 'react'
import { format, startOfWeek, addDays, isSameDay } from 'date-fns'
type Mood = '😊' | '😐' | '😢' | '😡' | '🤔'
const moods: Mood[] = ['😊', '😐', '😢', '😡', '🤔']
const moodColors: Record
'😊': 'bg-green-200',
'😐': 'bg-yellow-200',
'😢': 'bg-blue-200',
'😡': 'bg-red-200',
'🤔': 'bg-purple-200',
}
export default function MoodTracker() {
const [selectedMood, setSelectedMood] = useState
const [moodHistory, setMoodHistory] = useState
const handleMoodSelect = (mood: Mood) => {
setSelectedMood(mood)
const today = format(new Date(), 'yyyy-MM-dd')
setMoodHistory(prev => ({ ...prev, [today]: mood }))
}
const renderWeek = () => {
const startDate = startOfWeek(new Date())
return Array.from({ length: 7 }).map((_, index) => {
const date = addDays(startDate, index)
const dateString = format(date, 'yyyy-MM-dd')
const mood = moodHistory[dateString]
return (
className={`w-10 h-10 rounded-full flex items-center justify-center text-2xl ${mood ? moodColors[mood] : 'bg-gray-100'}`}
>
{mood || ''}
)
})
}
const renderMoodStats = () => {
const moodCounts = Object.values(moodHistory).reduce((acc, mood) => {
acc[mood] = (acc[mood] || 0) + 1
return acc
}, {} as Record
return moods.map(mood => (
{mood}
className={`${moodColors[mood]} h-4 rounded-full`}
style={{ width: `${((moodCounts[mood] || 0) / Object.keys(moodHistory).length) * 100}%` }}
>
))
}
return (
Mood Tracker
How are you feeling today?
{moods.map(mood => (
))}
This Week
{renderWeek()}
Mood Distribution
{renderMoodStats()}
)
}
扫描二维码分享
评论区
请登录后发表评论。