我有一个反应钩式表格和yup验证。我要做的是用react number格式格式化输入,但也将浮点值传递给验证和提交。
这是代码框:https://codesandbox.io/s/keen-field-26ub7
在InvoiceData.js中,有一个响应-数字格式正在使用的输入。我想根据上面的值(grossValue)验证这个输入,但是我认为如果不解析要再次浮动的值,我就不能这样做。
发布于 2021-03-23 07:51:31
我想我找到了一个答案建筑在亚历山大艾略特在第二个解决方案的基础上。我没有将amountToPay传递给onSubmit函数,而是将它传递给NumberFormat本身。
<NumberFormat
customInput={TextField}
inputRef={register}
variant="outlined"
name="amountToPay"
label={t('InvoiceData.amountToPay')}
helperText={
/* eslint-disable-next-line */
amountToPay> invoice.amountGross
? 'cannot be greater that amount gross'
: amountToPay=== 0
? 'cannot be 0'
: null
}
error={amountToPay> invoice.amountGross || amountToPay=== 0}
thousandSeparator={' '}
suffix=" PLN"
defaultValue={invoice.amountToPay}
onValueChange={(value) => handleValueChange(value.floatValue)}
decimalScale={2}
fixedDecimalScale
/>发布于 2021-03-22 11:37:50
第一解
在NumberFormat中创建一个InvoiceData类,并使用相同的格式化道具检索其removeFormatting函数
InvoiceData.js
const getProperties = ({ invoice, register, errors }) => ({
customInput: TextField,
inputRef: register,
variant: "outlined",
name: "amountToPay",
label: "InvoiceData.amountToPay",
helperText: ((errors || {}).amountToPay || {}).message,
error: (errors || {}).amountToPay,
thousandSeparator: " ",
suffix: " PLN",
defaultValue: (invoice || {}).amountToPay,
decimalScale: 2,
fixedDecimalScale: true
});
export const removeFormatting = (value, props = {}) => {
const properties = getProperties(props);
let res = Number.parseFloat(
new NumberFormat(properties).removeFormatting(value)
);
if (properties.decimalScale) {
return res * Math.pow(10, -properties.decimalScale);
}
return res;
};然后,您可以使用该函数检查提交的表单是否有效:
Form.js
const onSubmit = async (data) => {
if (removeFormatting(data.amountToPay) === responseData.amountGross) {
// action when valid
console.log("valid");
} else {
// action when invalid
}
};请参阅使用以下链接修改的代码:https://codesandbox.io/s/heuristic-paper-4ycuh
第二解
使用状态来记住amountToPay,如下所示:
const [amountToPay, setAmountToPay] = useState(responseData.amountToPay)向InvoiceData组件添加回调函数,并使用NumberFormat中的onValueChange调用该函数,例如:
const InvoiceData = ({...props, handleChanged} => {
return (
<NumberFormat
// whatever props you need
onValueChange={(value) => handleChanged(value.floatValue)}
/>
);
}然后,您可以传递我们之前定义的setAmountToPay,并以这种方式将它传递给InvoiceData:
<InvoiceData
// whatever props you need
handleChanged={setAmountToPay}
/>然后,您可以按照以下方式验证您的提交
const onSubmit = async () => {
if (amountToPay === responseData.amountGross) {
// action when valid
console.log("valid");
} else {
// action when invalid
}
};https://stackoverflow.com/questions/66669781
复制相似问题