如何清除React中的输入字段

问题描述 投票:0回答:2

因此,按

<button type="submit" className="btn btn-primary">Create</button>
后,我创建了一张带有英雄的卡片。然后
 .then(() => clearFields())
帮助我清除输入字段,因为再次单击“创建”按钮会返回一张空白卡。也就是说,我看到卡上的信息已正确清除。但从视觉上看,这些字段仍然被填满。

如何在按

<button type="submit" className="btn btn-primary">Create</button>
后使输入字段清晰?

import { useState, useEffect } from "react";
import { v4 as uuidv4 } from 'uuid';
import { useDispatch } from 'react-redux';
import { heroCreate } from '../../actions';
import { useHttp } from '../../hooks/http.hook';

const HeroesAddForm = () => {
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [element, setElement] = useState('');
    const {request} = useHttp();

    const dispatch = useDispatch();

    const clearFields = () => {
        setName('');
        setDescription('');
        setElement('');
    }
    const handleSubmit = (event) => {
        event.preventDefault();

        const newHero = {
            id: uuidv4(),
            name: name,
            description: description,
            element: element
        }
        request("http://localhost:3001/heroes", "POST", JSON.stringify(newHero))
        .then(dispatch(heroCreate(newHero)))
        .then(() => clearFields())
        .catch(err => console.log(err));   
        
    }
    return (
        <form className="border p-4 shadow-lg rounded" onSubmit={handleSubmit}>
            <div className="mb-3">
                <label htmlFor="name" className="form-label fs-4">Name of new hero</label>
                <input
                    required
                    type="text"
                    name="name"
                    className="form-control"
                    // id="name" 
                    onChange={event => setName(event.target.value)}
                    placeholder="What is your name?" />
            </div>

            <div className="mb-3">
                <label htmlFor="text" className="form-label fs-4">Description</label>
                <textarea
                    required
                    name="text"
                    className="form-control"
                    // id="text" 
                    placeholder="Tell us something about your hero"
                    onChange={event => setDescription(event.target.value)}
                    style={{ "height": '130px' }} />
            </div>

            <div className="mb-3">
                <label htmlFor="element" className="form-label">Choose hero element</label>
                <select
                    required
                    className="form-select"
                    id="element"
                    onChange={event => setElement(event.target.value)}
                    name="element">
                    <option >I have the element of...</option>
                    <option value="fire">Fire</option>
                    <option value="water">Water</option>
                    <option value="wind">Wind</option>
                    <option value="earth">Earth</option>
                </select>
            </div>

            <button type="submit" className="btn btn-primary">Create</button>
        </form>
    )
}

export default HeroesAddForm;

我这样编写代码是因为我认为

.then(() => clearFields())
会在执行查询并分派操作创建者后清除字段。

javascript reactjs redux react-redux jsx
2个回答
0
投票

你可以试试这个:

const handleSubmit = async (e) => {
  e.preventDefault();

  // Perform your post request here, e.g., using fetch or axios

  try {
    // Assuming a successful post request
    await postData(formData);

    // Clear form fields after successful post
    setFormData({
      fieldName1: '',
      fieldName2: '',
    });
  } catch (error) {
    console.error('Error submitting form:', error);
  }
};

0
投票

问题

当然,

clearFields
处理程序会重置本地
name
description
element
状态值,但由于您的表单字段不是完全受控,它们实际上不会更新,直到您手动编辑输入。

PUT 请求响应处理中还存在一个小问题,即立即调用

dispatch
,而不是在
request
解决之后。

解决方案

你有 2 个简单的选择:

完全控制输入

完全控制的输入使用 React 状态,并将

value
onChange
处理程序传递给输入。换句话说,该值是由国家控制的。

const HeroesAddForm = () => {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [element, setElement] = useState("");
  const { request } = useHttp();

  const dispatch = useDispatch();

  const clearFields = () => {
    setName("");
    setDescription("");
    setElement("");
  };

  const handleSubmit = (event) => {
    event.preventDefault();

    const newHero = {
      id: uuidv4(),
      name,
      description,
      element
    };

    request("http://localhost:3001/heroes", "POST", JSON.stringify(newHero))
      .then(() => dispatch(heroCreate(newHero))) // <-- arrow function call dispatch
      .then(clearFields)
      .catch(console.log);
  };

  return (
    <form className="border p-4 shadow-lg rounded" onSubmit={handleSubmit}>
      <div className="mb-3">
        <label htmlFor="name" className="form-label fs-4">
          Name of new hero
        </label>
        <input
          required
          type="text"
          name="name"
          className="form-control"
          onChange={(event) => setName(event.target.value)}
          value={name} // <-- provide value
          placeholder="What is your name?"
        />
      </div>

      <div className="mb-3">
        <label htmlFor="text" className="form-label fs-4">
          Description
        </label>
        <textarea
          required
          name="description"
          className="form-control"
          placeholder="Tell us something about your hero"
          onChange={(event) => setDescription(event.target.value)}
          value={description} // <-- provide value
          style={{ height: "130px" }}
        />
      </div>

      <div className="mb-3">
        <label htmlFor="element" className="form-label">
          Choose hero element
        </label>
        <select
          required
          className="form-select"
          id="element"
          onChange={(event) => setElement(event.target.value)}
          value={element} // <-- provide value
          name="element"
        >
          <option disabled value="">
            I have the element of...
          </option>
          <option value="fire">Fire</option>
          <option value="water">Water</option>
          <option value="wind">Wind</option>
          <option value="earth">Earth</option>
        </select>
      </div>

      <button type="submit" className="btn btn-primary">
        Create
      </button>
    </form>
  );
};

完全不受控制的输入

完全不受控制的输入不使用 React 状态,也不将

value
onChange
处理程序传递给输入。使用
form
元素的
onSubmit
处理程序访问表单字段值并重置表单。

const HeroesAddForm = () => {
  const { request } = useHttp();

  const dispatch = useDispatch();

  const handleSubmit = (event) => {
    event.preventDefault();

    const { description, element, name } = event.target;

    const newHero = {
      id: uuidv4(),
      name: name.value,
      description: description.value,
      element: element.value
    };

    request("http://localhost:3001/heroes", "POST", JSON.stringify(newHero))
      .then(() => dispatch(heroCreate(newHero)))
      .then(() => event.target.reset())
      .catch(console.log);
  };

  return (
    <form className="border p-4 shadow-lg rounded" onSubmit={handleSubmit}>
      <div className="mb-3">
        <label htmlFor="name" className="form-label fs-4">
          Name of new hero
        </label>
        <input
          required
          type="text"
          name="name"
          className="form-control"
          placeholder="What is your name?"
        />
      </div>

      <div className="mb-3">
        <label htmlFor="text" className="form-label fs-4">
          Description
        </label>
        <textarea
          required
          name="description"
          className="form-control"
          placeholder="Tell us something about your hero"
          style={{ height: "130px" }}
        />
      </div>

      <div className="mb-3">
        <label htmlFor="element" className="form-label">
          Choose hero element
        </label>
        <select
          required
          className="form-select"
          id="element"
          defaultValue="" // <-- default value
          name="element"
        >
          <option disabled value="">
            I have the element of...
          </option>
          <option value="fire">Fire</option>
          <option value="water">Water</option>
          <option value="wind">Wind</option>
          <option value="earth">Earth</option>
        </select>
      </div>

      <button type="submit" className="btn btn-primary">
        Create
      </button>
    </form>
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.