fix: percent value invalid (#2782)

* fix: percent value invalid

* fix: useMemo
This commit is contained in:
chenos 2023-10-10 11:54:46 +08:00 committed by GitHub
parent 79f9e04413
commit bccec4385a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,29 +1,36 @@
import { connect, mapReadPretty } from '@formily/react';
import { isNumberLike } from '@formily/shared';
import { InputNumber } from 'antd';
import * as math from 'mathjs';
import React from 'react';
import React, { useMemo } from 'react';
import { ReadPretty } from '../input-number/ReadPretty';
const toValue = (value: any, callback: (v: number) => number) => {
if (isNumberLike(value)) {
return math.round(callback(value), 9);
}
return null;
};
export const Percent = connect(
(props) => {
const { value, onChange } = props;
const v = useMemo(() => toValue(value, (v) => v * 100), [value]);
return (
<InputNumber
{...props}
addonAfter="%"
defaultValue={value ? math.round(value * 100, 9) : null}
formatter={(v: any) => (v ? math.round(v * 100, 9) : null)}
value={v}
onChange={(v: any) => {
if (onChange) {
const val = v ? math.round(v / 100, 9) : 0;
onChange(val);
onChange(toValue(v, (v) => v / 100));
}
}}
/>
);
},
mapReadPretty((props) => {
return <ReadPretty {...props} value={props.value ? math.round(props.value * 100, 9) : null} />;
const value = useMemo(() => toValue(props.value, (v) => v * 100), [props.value]);
return <ReadPretty {...props} value={value} />;
}),
);