调整购买页面价格显示

This commit is contained in:
Eamon-meng
2026-06-18 15:11:28 +08:00
parent 96abb97a9a
commit c297c2330e
11 changed files with 111 additions and 25 deletions

View File

@@ -9,12 +9,37 @@ export type FormOptionProps = {
value: string
label?: string
description?: string
price?: string
discount?: number
compare: string
className?: string
children?: ReactNode
}
export default function FormOption(props: FormOptionProps) {
// 安全地解析价格
const priceNum = props.price ? parseFloat(props.price) : NaN
const isValidPrice = !isNaN(priceNum) && priceNum > 0
const discount = typeof props.discount === 'number' ? props.discount : undefined
const hasDiscount = isValidPrice && discount !== undefined && discount < 100
const discountedPrice = hasDiscount ? priceNum * discount / 100 : null
const formatPrice = (price: number | string): string => {
const num = typeof price === 'string' ? parseFloat(price) : price
// 如果是 NaN 或无效值,返回空字符串
if (isNaN(num) || !isFinite(num)) return ''
const str = num.toString()
if (!str.includes('.')) return str
const decimal = str.split('.')[1]
if (/^0+$/.test(decimal)) return Math.floor(num).toString()
if (decimal.length <= 2) return str
return num.toFixed(4).replace(/\.?0+$/, '')
}
return (
<>
<FormLabel
@@ -28,7 +53,24 @@ export default function FormOption(props: FormOptionProps) {
{props.children ? props.children : (
<>
<span>{props.label}</span>
{props.description && <p className="text-sm text-gray-500">{props.description}</p>}
{props.description && !isValidPrice && (
<p className="text-sm text-gray-500">{props.description}</p>
)}
{isValidPrice && (
<div className="flex items-center gap-2 flex-wrap">
{hasDiscount ? (
<>
<p className="text-sm font-medium">{formatPrice(discountedPrice!)}/IP</p>
<p className="text-sm text-gray-500 line-through">:{formatPrice(props.price!)}/IP</p>
{/* <span className="text-xs font-medium text-orange-600 bg-orange-50 px-1.5 py-0.5 rounded-full">
{props.discount}折
</span> */}
</>
) : (
<p className="text-sm">{formatPrice(props.price!)}/IP</p>
)}
</div>
)}
</>
)}
</FormLabel>