如何获得floatValue自动从反应数字格式在一个andd Form.Item?



我正在寻找一种方法表单自动从react-number-format中获取floatValue。

`<Form.Item
label="My label"
name="fator"
>
<NumericFormat
thousandSeparator="."
decimalSeparator=","
decimalScale={2}
prefix="R$"
fixedDecimalScale={true}
onValueChange={(values, sourceInfo) => {
setState({
...state,
fator: values.floatValue!,
});
}}
/>
</Form.Item>`

有些人使用onValueChange来获取floatValue,但我不知道这是否是获得该值的唯一方法或最佳方法。通过这种方式,我们必须检查每个字段以分配正确的值。在我看来,这不是最好的方式。这是手工工作。

const submit = async (values: stateModel) => {values.fator = state.fator;......await doRegister(values);..}

解决这个问题的最好方法是什么?我尝试使用一些替换从表单提交返回的值,但这不是解决问题的最佳方法。

你可以通过创建一个自定义的Number Field来解决这个问题,它将value和onChange作为props。

const CustomNumberField = ({ value, onChange }) => {
return (
<NumericFormat
value={value}
thousandSeparator='.'
decimalSeparator=','
decimalScale={2}
prefix='R$'
fixedDecimalScale={true}
onValueChange={(values, sourceInfo) => {
onChange(values.floatValue);
}}
/>
);
};

现在主表单看起来像这样:

const App = () => {
return (
<Form
onFinish={(values) => {
console.log(values); // { factor: 12 }
}}
>
<Form.Item label='My label' name='fator'>
<CustomNumberField />
</Form.Item>
{/* OR */}
{/* <Form.Item name='field'>
{(control, meta, form) => {
return <CustomNumberField {...control} />;
}}
</Form.Item> */}
<Button htmlType='submit'>Submit</Button>
</Form>
);
};

Q:value&onChange道具从何而来?

当您将nameprop传递给Form.Item时,表单内的字段。物品现在由Form控制。您可以传递一个ReactElement或一个函数。对于ReactElement,它传递两个道具value&onChange。对于回调函数,它看起来像这样:

children?: React.ReactElement | ((control: ChildProps, meta: Meta, form: FormInstance<Values>) => React.ReactNode);
interface ChildProps {
[name: string]: any;
}
interface Meta {
touched: boolean;
validating: boolean;
errors: string[];
warnings: string[];
name: InternalNamePath;
}
type InternalNamePath = (string | number)[];

最新更新