“心情♥追踪器”卡片组件

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(null)

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 (

{format(date, 'EEE')}

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 => (

key={mood}

onClick={() => handleMoodSelect(mood)}

className={`text-4xl p-2 rounded-full transition-all duration-200 ${selectedMood === mood ? 'bg-gray-200 transform scale-110' : ''}`}

>

{mood}

))}


This Week

{renderWeek()}


Mood Distribution

{renderMoodStats()}

)

}

×
二维码

扫描二维码分享

评论区

登录后发表评论。