@dcg-overseas/unit-conver
v0.3.1
Published
Unit conversion tool
Keywords
Readme
@dcg-overseas/unit-conver
小学数学单位换算组件。展示"输入框 ⇌ 结果框"的换算区域;类别切换、公式下拉等选择 UI 由使用方实现(数据从本包导出)。
换算结果用十进制移位精确计算(当前公式比率均为 10 的幂),任意长度输入不丢精度;若未来引入非 10 幂比率,结果被舍入时会带 ≈ 前缀。
安装
pnpm add @dcg-overseas/unit-converPeer Dependencies:
react >= 18,react-dom >= 18
import '@dcg-overseas/unit-conver/style.css'使用
组件是受控的:category / formulaIndex 由使用方持有,切换 UI 自行渲染。外框装饰(背景、圆角、内边距、高度)也由使用方提供,组件只负责框内布局;横排数字框高度跟随容器伸缩(default 钳制 110–200px,compact 80–120px)。
import { useRef, useState } from 'react'
import {
UnitConver,
CATEGORIES,
getCategory,
type Category,
type UnitConverHandle,
} from '@dcg-overseas/unit-conver'
function Demo() {
const ref = useRef<UnitConverHandle>(null)
const [category, setCategory] = useState<Category>('length')
const [formulaIndex, setFormulaIndex] = useState(
() => getCategory('length').defaultFormulaIndex,
)
return (
<>
{/* 使用方自绘类别 Tab / 公式下拉,数据来自 CATEGORIES */}
{CATEGORIES.map((c) => (
<button
key={c.key}
onClick={() => {
setCategory(c.key)
setFormulaIndex(getCategory(c.key).defaultFormulaIndex)
}}
>
{c.label}
</button>
))}
{/* 外框装饰由使用方控制 */}
<div className="h-[424px] rounded-[40px] bg-[#FFFDF7] px-[40px] py-[71px]">
<UnitConver
ref={ref}
layout="horizontal"
category={category}
formulaIndex={formulaIndex}
/>
</div>
<button onClick={() => ref.current?.reset()}>清除</button>
</>
)
}API
<UnitConver />
| Prop | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| layout | 'horizontal' \| 'vertical' | 'horizontal' | 横排(左右卡片)或竖排(上下卡片) |
| size | 'default' \| 'compact' | 横排 'default',竖排 'compact' | compact 用于小弹窗,字号/间距更紧凑 |
| category | Category | 'area' | 当前类别(受控) |
| formulaIndex | number | 类别的 defaultFormulaIndex | 当前公式下标(受控) |
| defaultValue | number | 0 | 输入框初始值 |
| className | string | — | 附加到根节点 |
category / formulaIndex 变化时组件自动清除交换方向。
UnitConverHandle
| 方法 | 说明 |
|------|------|
| reset() | 重置输入值与交换方向;类别/公式的重置由使用方自行处理 |
数据与工具
| 导出 | 说明 |
|------|------|
| CATEGORIES | 全部类别定义(length / area / mass / volume),用于自绘选择 UI |
| getCategory(key) | 按 key 取类别,未命中回退第一个 |
| getUnit(category, value) | 按 value 取单位定义 |
| formatNumber(value) | 结果格式化:整数原样;≥1 最多 6 位小数;<1 取 6 位有效数字;不做千分位分组 |
| computeConversionText(input, ratio, swapped) | 由输入串直接算结果串;10 幂比率走十进制移位(精确),其余回退浮点并在舍入时加 ≈ |
| shiftDecimalPoint(raw, exp) | 十进制数字串小数点移位,纯字符串运算 |
类型
Category('length' \| 'area' \| 'mass' \| 'volume')、CategoryDef、FormulaDef、UnitDef。
开发
pnpm build # 构建
pnpm build:watch # 监听模式
pnpm typecheck # 类型检查