如何保持文本字段为0?清除文本字段将导致另一个值为isNaN



如果我将其作为空白字段,这将导致total显示为isNaN,如果它是isNaN,我不希望提交表单。如果total值显示为isNaN,我如何阻止表单被提交?

export default function BasicTextFields() {
const [fee, setFee] = useState(0);
const amount = parseInt(1000);
const total = Number(amount) + Number(fee);
const handleSubmit = async (e) => {
e.preventDefault();
console.log(" submit");
};
return (
<form onSubmit={{ handleSubmit }}>
<TextField
label="Fee"
type="number"
value={fee}
onChange={(e) => setFee(parseInt(e.target.value))}
InputProps={{
inputProps: {
min: 0
}
}}
/>
<button type="submit">Submit</button>
<br />
Total: {total}
</form>
);
}

codesandbox: https://codesandbox.io/s/basictextfields-material-demo-forked-7sfdph?file=/demo.js: 171 - 809

可以使用

onChange={(e) => {
if(e.target.value===""){
setFee(0);
}else{
setFee(parseInt(e.target.value))}}
}
import React, { useState } from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
export default function BasicTextFields() {
const [fee, setFee] = useState(0);
const amount = parseInt(1000);
const total = Number(amount) + Number(fee);
// async is not required if you are not using await keywork in function.
const handleSubmit = (e) => {
e.preventDefault();
if (isNaN(fee)) {
console.log("its not a number");
} else {
console.log("its a number");

// this submit will refresh page.
// e.target.submit();

// if you do not want page to refresh.
// remeber there is different approch for image data.
var formData = new FormData();
formData.append('fee', fee);
console.log(formData);
// continue with sending data to your backend server
}
};
const changeFee = (e) => {
setFee(e.target.value);
}
return (
// use only one curly braces
<form onSubmit={handleSubmit}>
<TextField
label="Fee"
type="text"
value={fee}
onChange={changeFee}
InputProps={{
inputProps: {
min: 0
}
}}
/>
<button type="submit">Submit</button>
<br />
Total: {total}
</form>
);
}

阅读上面代码中提到的所有注释,可能会有所帮助。

最新更新