簡體   English   中英

提交時如何清除我的反應表單?

[英]How can I clear my react form when it is submitted?

我制作了兩個反應組件FormInput 提交表單時如何使Form中的Input組件為空白? 另一個問題:你認為表單里面的Input組件是不必要的,因為我的項目只有一個表單嗎?

// 輸入.js

export const Input = ({ id, className, onKeyUp, value }) => {
  return (
    <>
      <input
        type="text"
        id={id}
        className=""
        onKeyUp={onKeyUp}
        value={value}
      />
    </>
  );
};

// Form.js

export const Form = ({ addData }) => {
  const [userData, setUserData] = useState({
    weight: "",
    height: "",
    bmi: null,
    date: new Date().toISOString().split("T")[0],
  });

  const initialState = {
    weight: "",
    height: "",
    bmi: null,
    date: new Date().toISOString().split("T")[0],
  }

  function sendDataToApp(e) {
    e.preventDefault();
    const heightSquared = Math.pow(userData.height / 100, 2);
    const calculateBMI = userData.weight / heightSquared;
    userData.bmi = calculateBMI;
    addData(userData);
    setUserData({...initialState});

  }

  return (
    <div className="">
      <form
        className=""
        onSubmit={sendDataToApp}
      >
        <Inputlabel
          htmlFor="weight"
          className=""
        />
        <Input
          className=""
          id="weight"
          onKeyUp={(e) => setUserData({ ...userData, weight: e.target.value })}
          value={userData.weight}
        />
        <Inputlabel
          htmlFor="height"
          className=""
        />
        <Input
          className=""
          id="height"
          onKeyUp={(e) => setUserData({ ...userData, height: e.target.value })}
          value={userData.height}
        />
        <input
          type="submit"
          value="submit"
          className=""
          disabled={userData.weight === null || userData.height === null}
        />
      </form>
    </div>
  );
};

// App.js

export const App = () => {
  const [bmi, setBmi] = useState([]);

  function bmiToHook(newBmi) {
    setBmi([...bmi, newBmi]);
    console.log(bmi);
  }
  return (
    <div className="">
      <Title />
      <Form addData={bmiToHook} />
      <Chart dataToChart={bmi}/>
    </div>
  );
};

HTML forms 內置了一個reset()方法,您可以利用它。 您可以使用useRef()訪問<form>元素。

export const Form = ({ addData }) => {
  const ref = useRef(null);

  ...

  function sendDataToApp(e) {
    e.preventDefault();
    ref.current.reset() // <-- add this line. 
    // You probably want to add it after validation though
    ...
  }

  return (
    <div className="">
      <form
        className=""
        onSubmit={sendDataToApp}
        ref={ref}
      >
      ...
      </form>
    </div>
  );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM