我正在一个React项目上,我试图在react中单击“提交”按钮后重置一个表单,但是它不起作用。单击提交按钮后,我正在使用useRef钩子重置表单。 但是不能正常工作。所以有人请帮我单击提交按钮后如何重设表单。
这是我的代码
import React, { useState, useRef } from 'react';
import './Signup.css';
import axios from 'axios';
export default function Signup() {
const [data, setData] = useState({});
const testData = async () => {
try {
const res = await axios.post('http://localhost:8000/api/user', data);
console.log(res);
} catch (error) {
console.log(error);
}
}
const handleChange = ({ target }) => {
const { name, value } = target;
const newData = Object.assign({}, data, { [name]: value });
setData(newData);
}
const handleSubmit = (e) => {
e.preventDefault();
console.log(data);
testData()
};
const myForm = useRef(null)
const resetForm = () => {
myForm.current.reset();
}
return (
<div>
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="firstname">Firstname</label>
<input type="text" className="form-control" placeholder='firstname' id="firstname" name='firstname' onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="lastname">Lastname</label>
<input type="text" className="form-control" placeholder='lastname' id="lastname" name='lastname' onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" placeholder='email' id="email" name='email' onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" placeholder='password' id="password" name='password' onChange={handleChange}></input>
</div>
<button ref={myForm} onSubmit={resetForm} type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
答案 0 :(得分:1)
应该是
<form onSubmit={handleSubmit} ref={myForm}>
和
<button
onClick={resetForm}
type="submit"
className="btn btn-primary"
>