看到網上寫的rate
組件,要麼是react的class方式,要麼就是基於classNameList
的增刪改查,總感覺不太完美,於是趁週末自己擼了一個,可以直接拿到自己的頁面去試,喜歡請點個贊哦
需求分解:默認全不點亮 ,右側默認
請選擇評分
,點擊時,點擊的那個小心心左邊全部呈紅色,鼠標經過小心心時,小心心呈紅色,移出時,如果移入前有被點擊,則回退到點擊態,否則全不點亮:
import React, { useState } from 'react'
function Rate({ rateList, defaultRate }) {
// 使用 useState 定義當前的 rate 狀態、上一次點擊的 rate 狀態和是否有進行過點擊的狀態
const [currentRate, setCurrentRate] = useState(defaultRate ? defaultRate : 0)
const [lastClickedRate, setLastClickedRate] = useState(defaultRate ? defaultRate : 0)
const [clicked, setClicked] = useState(false)
// 根據當前 rate 和 clicked 狀態,生成樣式對象
const getStyle = rate => {
console.log('rate :>> ', rate)
console.log('currentRate :>> ', currentRate)
return clicked && rate <= currentRate ? { color: 'red' } : {}
}
// 點擊事件處理函數,更新當前的 rate 狀態、上一次點擊的 rate 狀態和 clicked 狀態
const handleClick = rate => {
console.log('rate :>handleClick> ', rate)
// 設置當前rate
setCurrentRate(rate)
// 設置上一次點擊時的rate
setLastClickedRate(rate)
// 設置已經點擊
setClicked(true)
}
// 鼠標移入事件處理函數,更新當前的 rate 狀態
const handleMouseEnter = rate => {
setCurrentRate(rate)
console.log('rate :>setCurrentRate> ', rate)
}
// 鼠標移出事件處理函數,更新當前的 rate 狀態爲上一次點擊的 rate 狀態
const handleMouseLeave = () => {
setCurrentRate(lastClickedRate)
}
return (
<div style={{ display: 'flex', margin: '200px 300px' }}>
{/* 遍歷 rateList,生成相應的 div 元素 */}
{rateList.map((rate, index) => (
<div
key={index}
style={{ paddingRight: '18px', ...getStyle(index + 1) }}
onClick={() => handleClick(index + 1)}
onMouseEnter={() => handleMouseEnter(index + 1)}
onMouseLeave={handleMouseLeave}>
❤
</div>
))}
{/* 顯示當前 rate 對應的名字 */}
<div>{rateList[currentRate - 1] ? rateList[currentRate - 1] : '請選擇評分'}</div>
</div>
)
}
export default Rate
以上。