简体   繁体   English

可以使用 useRef 钩子来清空输入值吗?

[英]can use useRef hook to empty the input value?

I used useRef at this component and it's work well when I need to refer to the input value, but when I finish and click the submit button, it's work well but the input field still have the work I wrote我在这个组件上使用了 useRef ,当我需要引用输入值时它工作得很好,但是当我完成并单击提交按钮时,它工作得很好但输入字段仍然有我写的工作

simply, I need to empty the input field when click submit, Without using useState and Onchange function because it causes too renders简单地说,我需要在单击提交时清空输入字段,而不使用 useState 和 Onchange 函数,因为它会导致渲染太多

is there any method at useRef that helps me to empty the input field useRef 是否有任何方法可以帮助我清空输入字段

here is the Code这是代码


const AddTodoForm = () => {
  const inputRef = useRef()

  const createTodo = (e) => {
    e.preventDefault()
    const todoRef = fire.database().ref("Todo");
    const todo = {
      title: inputRef.current.value,
      complete: false
    };
    todoRef.push(todo)

    // I Need To Empty input value here

  }

  return (
    <form>
      <input type="text" ref={inputRef} />
      <button onClick={createTodo}> Add Todo </button>
    </form>
  )
}

Clear the input after submit the to do is the way.提交后清空输入就是这样。

  const AddTodoForm = () => {
  const inputRef = useRef()

  const createTodo = (e) => {
    e.preventDefault()
    const todoRef = fire.database().ref("Todo");
    const todo = {
      title: inputRef.current.value,
      complete: false
    };
    todoRef.push(todo)
    inputRef.current.value = ""
  }

  return (
    <form>
      <input type="text" ref={inputRef} />
      <button onClick={createTodo}> Add Todo </button>
    </form>
  )
}

Just get current DOM in rer and set value ""( inputRef.current.value = ""; ).只需在inputRef.current.value = "";获取当前 DOM 并设置值 ""( inputRef.current.value = ""; )。 Example:例子:

import React, { useRef, useState } from "react";

export default function DisableElevation() {
  const [todos, setTodos] = useState([]);

  const addTodo = (todo) => {
    setTodos([...todos, todo]);
  };

  return (
    <div>
      <AddTodoForm addTodo={(todo) => addTodo(todo)} />

      {todos.map((todo) => (
        <div> {todo.title} </div>
      ))}
    </div>
  );
}

const AddTodoForm = ({ addTodo }) => {
  const inputRef = useRef();

  const createTodo = (e) => {
    e.preventDefault();
    const todo = {
      title: inputRef.current.value,
      complete: false
    };

    inputRef.current.value = "";
    addTodo(todo);

    // I Need To Empty input value here
  };

  return (
    <form>
      <input type="text" ref={inputRef} />
      <button onClick={createTodo}> Add Todo </button>
    </form>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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