2

I have an input field and I handle the input via onKeyUp (as I need to access event.which). This works great so far as I just grab the content of the input via event.target.value but I run into issues when I try to reset the value of the input field.

I'm using functional components, so accessing the input via refs isn't possible and all examples I found with useRef just show how to focus the input field but not how to clear it.

I forgot to mention that I'm using Material-UI.

4

4 回答 4

5

ref.current.value您可以通过强制设置为空字符串来使用功能组件内的 ref 清除输入值:

const App = () => {
  const textInput = React.useRef();

  const clearInput = () => (textInput.current.value = "");

  return (
    <>
      <input type="text" ref={textInput} />
      <button onClick={clearInput}>Reset</button>
    </>
  );
}
于 2019-10-20T19:08:14.663 回答
3

我当前的解决方案使用 onChange 来更新值的状态,并使用 onKeyUp 来处理输入(并最终重置值):

export default function TypingArea() {
const [inputValue, setInputValue] = useState('');

const handleChange = event => {
  setInputValue(event.target.value);
};

const handleInput = event => {
  // access event.which for the keycode and eventually clear the inputfield value
  setInputValue('');
}  

return (
<TextField
  onChange={handleChange}
  onKeyUp={handleInput}
  type='text'
  value={inputValue} />);
}

我可能会遇到此设置的问题,因为我不确定谁先运行,onChange 或 onKeyUp,但它现在有效。

于 2019-10-21T08:27:03.573 回答
0

考虑到您正在使用功能组件,您可以执行 e.target.reset 。

 const [state, setState] = React.useState({ username: "", password: "" });

  const handleSubmit = e => {
    e.preventDefault();
    console.log(state);
    

e.target.reset();

  };
const handleChange = e => {
    setState({
      ...state,
      [e.target.name]: e.target.value
    });
  };
  return (
    <div className="App">
      <h1>Log In</h1>
      <form onSubmit={handleSubmit}>
        <input
          className="userInput"
          name="username"
          type="text"
          placeholder="username"
          onChange={handleChange}
        />
        <br />
        <input
          className="userInput"
          name="password"
          type="password"
          placeholder="password"
          onChange={handleChange}
        />
        <br />
        <input className="userSubmit" type="submit" value="Log In" />
      </form>
    </div>
  );
}
于 2021-05-05T11:16:09.750 回答
-2
const [tasks, setTasks] = useState([]);
const [input, setInput] = useState(' ');


Const addTask = () => {
       setTasks([...tasks, input])
       SetInput(' ')

}
return (
  <button onClick={addTasks}/>Add Task <button/>
)
于 2022-02-04T11:28:15.683 回答