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

时间:2020-09-14 12:10:39

标签: javascript reactjs react-hook-form

我在该组件上使用过useRef,当我需要引用输入值时,它工作得很好,但是当我完成并单击提交按钮时,它就很好了,但是输入字段仍然有我写的工作

简而言之,我需要在单击提交时清空输入字段,不使用useState和Onchange函数,因为它也会导致渲染

在useRef上有什么方法可以帮助我清空输入字段

这是代码


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>
  )
}

2 个答案:

答案 0 :(得分:2)

提交后清除输入是方法。

  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>
  )
}

答案 1 :(得分:0)

只需获取rer中的当前DOM并将值设置为“”(inputRef.current.value = "";)。示例:

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>
  );
};