如何解析 react-final-form 中未触及的字段
How to parse untouched fields in react-final-form
我有一个反应最终形式的金额输入。如果没有填写,我需要将其表单值设置为零。我无法将初始值传递给它,就好像它还没有被用户填充一样,输入本身应该保持为空。
在 react-final-form 文档中有一个 parse 函数。但它仅在该字段已被触摸(由用户填充然后清除)时才有效。有什么方法可以解析未触及的字段并将它们在表单值中设置为零,而不更新输入?
这是我的代码:
<Field
name="amount"
component={CurrencyInput}
parse={value => (value ? value : 0)}
/>
这是我 codesandbox 的 link。
如果通过这样做,您想要完成的是 <pre>
中显示的对象在输入为空时的默认值为零,您可以使用状态变量并在 parse
不断更新它的值
const [amount, setAmount] = useState(0);
const onInputChange = e => {
e === "" || e === undefined ? setAmount(0) : setAmount(e);
};
并在 Field
标签中
<Field
name="amount"
component={CurrencyInput}
parse={value => onInputChange(value)}
defaultValue={amount}
/>
在此处检查代码和框:
https://codesandbox.io/s/react-final-form-wreact-number-format-and-parse-22q3n
希望这能解决问题
我有一个反应最终形式的金额输入。如果没有填写,我需要将其表单值设置为零。我无法将初始值传递给它,就好像它还没有被用户填充一样,输入本身应该保持为空。
在 react-final-form 文档中有一个 parse 函数。但它仅在该字段已被触摸(由用户填充然后清除)时才有效。有什么方法可以解析未触及的字段并将它们在表单值中设置为零,而不更新输入?
这是我的代码:
<Field
name="amount"
component={CurrencyInput}
parse={value => (value ? value : 0)}
/>
这是我 codesandbox 的 link。
如果通过这样做,您想要完成的是 <pre>
中显示的对象在输入为空时的默认值为零,您可以使用状态变量并在 parse
不断更新它的值
const [amount, setAmount] = useState(0);
const onInputChange = e => {
e === "" || e === undefined ? setAmount(0) : setAmount(e);
};
并在 Field
标签中
<Field
name="amount"
component={CurrencyInput}
parse={value => onInputChange(value)}
defaultValue={amount}
/>
在此处检查代码和框:
https://codesandbox.io/s/react-final-form-wreact-number-format-and-parse-22q3n
希望这能解决问题