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

How to remain the textfield to 0? Clearing up the textfield will cause another value to isNaN

如果我将其保留为空白字段,这将导致 total 显示为 isNaN,如果是 [=13=,我不想提交表单].如果 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>
  );
}

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