简体   繁体   中英

(React.js + Hooks) How to reset input field after button click?

What I want to do is have an input that a user can type into. Upon clicking a button, take that input and process it and perform some backend operations with the database connected to the input. I'm trying to accomplish this with a state hook: onBlur, save input into state. On button click, do two things: 1) take the state variable and pass it to the backend resolvers, and 2) clear the input field so it's empty, and only the placeholder text exists.

I have this code:

const [inputVal, setInputVal] = useState("");

updateInput = (e) => {
    const val = e.target.value;
    setInputVal(val);
}

sendData = async () => {
    //handle async backend processing with inputVal
    setInputVal("");
    //rerender
}


<Button className="input-button" onClick={sendData}>Send Data</Button>
<input className="input-field" placeHolder="Input name." defaultValue={inputVal} onBlur=(updateInput)></input>

However, I have two issues.

  1. On button click, I want to first updateInput, and then handle the button click, so it always uses the new value. However, it seems as if there are some issues with that, possibly due to the asynchronous nature of sendData?

  2. While inputVal may be an empty String, for some reason, the value in the input box doesn't reset to nothing, it stays exactly as it was (although the internal data would still have inputVal = 0 ). And onBlur it reupdates the inputVal.

for a controlled state input the most common approach is to use onChange rather than onBlur . This would also avoid your conflicts with blur and click events. Also you would pass inputVal to value input's property.

  const [inputVal, setInputVal] = useState("");

  const updateInput = (e) => {
    const val = e.target.value;
    setInputVal(val);
  }

  const sendData = async () => {
    //handle async backend processing with inputVal
    setInputVal("");
    //rerender
  }

  return (
    <>
      <button className="input-button" onClick={sendData}>Send Data</button>
      <input className="input-field" onChange={updateInput} placeHolder="Input name." value={inputVal}/>
    </>
  );

First, change defaultValue to value={inputVal} since it's a controlled input. Secondly, please elaborate on what issues you have in 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM