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