带单位的 InputNumber
注意点:InputNumber手动删除值后,值为 null;不是 0,需要兼容下
import React, { useState, useEffect } from 'react';
import { string, func } from 'prop-types';
import { InputNumber, Select } from 'antd';
import { words, isFunction, isNil } from 'lodash-es';
export const options = [
{label: '秒', value: 's'},
{label: '分钟', value: 'm'},
{label: '小时', value: 'h'},
{label: '天', value: 'd'},
{label: '月', value: 'm'},
]
const initState = { value: 1, unit: 'm' }
function formatUnit({ value, unit }) {
return `${value}${unit}`;
}
InputNumberWithUnit.propTypes = {
value: string,
onChange: func,
};
function InputNumberWithUnit({ value, onChange }) {
const [state, setState] = useState(initState);
useEffect(() => {
const [val, unit = initState.unit] = words(value);
if (isNil(val)) return;
setState({ unit, value: val });
}, [value]);
function handleChange(key, val) {
setState(prevState => {
const _state = { ...prevState, [key]: val };
if (isFunction(onChange)) {
onChange(formatUnit(_state));
}
return _state;
});
}
return (
<InputNumber
value={state.value}
onChange={val => handleChange('value', val)}
min={0}
addonAfter={(
<Select
value={state.unit}
// 手动清空,值为 null
onChange={val => handleChange('unit', val: val ?? 0)}
options={options}
// 80px https://tailwindcss.com/docs/width
className='w-20'
/>
)}
/>
);
}
export default InputNumberWithUnit;