所以在按下<button type="submit" className="btn btn-primary">Create</button>
后,我创建了一张带有英雄的卡片.然后, .then(() => clearFields())
帮助我清除输入字段,因为с再次点击СReate按钮将返回一张空白卡片.也就是说,我看到卡上的信息被正确清除了.但从视觉上看,这些字段仍处于填充状态.
按下<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())
会在执行查询和调度操作创建者之后清除字段.