事情非常简单明了,我想在提交字段时清除我的输入字段。
状态:
const [formData, setFormData] = useState({
linkName: "",
link: ""
});
handleSubmit
函数:
Axios.post("/api/social", body, config)
.then(
setSocialList(prev => [
...prev,
{ _id: Math.random(), link, linkName }
])
)
.then(setFormData({ link: " ", linkName: " " }));
} catch (err) {
console.error(err);
}
这样我就无法清除我的 formData
状态,因此输入字段在提交时不会清除。
最佳答案
您需要将 link 和 linkName 的值与输入字段绑定(bind),否则该值会在状态中更新,但输入仍将具有输入的值,并且不会反射(reflect)任何以编程方式更新的值。
import React, { Fragment, useState, useContext } from "react";
import { Button, Form, FormGroup, Label, Input, Row, Col } from "reactstrap";
import Axios from "axios";
import { SocialContext } from "./SocialContext";
const SocialForm = () => {
const [formData, setFormData] = useState({
linkName: "",
link: ""
});
const [socialList, setSocialList] = useContext(SocialContext);
const { linkName, link } = formData;
const onChange = e =>
setFormData({ ...formData, [e.target.name]: e.target.value });
const token = localStorage.getItem("token");
const handleSubmit = e => {
e.preventDefault();
const socialList = {
linkName,
link
};
try {
const config = {
headers: {
"Content-Type": "application/json",
"x-auth-token": `${token}`
}
};
const body = JSON.stringify(socialList);
Axios.post("/api/social", body, config)
.then(
setSocialList(prev => [
...prev,
{ _id: Math.random(), link, linkName }
])
)
.then(setFormData({ link: " ", linkName: " " }));
} catch (err) {
console.error(err);
}
};
return (
<Fragment>
<br />
<Form onSubmit={e => handleSubmit(e)} className="socialForm">
<Row form>
<Col md={5}>
<FormGroup>
<Label for="LinkName">LinkName</Label>
<Input
type="text"
name="linkName"
value={linkName}
placeholder="Ex. Facebook"
onChange={e => onChange(e)}
/>
</FormGroup>
</Col>
<Col md={5}>
<FormGroup>
<Label for="Link">Link</Label>
<Input
type="text"
name="link"
value={link}
placeholder="Ex. https://www.facebook.com/"
onChange={e => onChange(e)}
/>
</FormGroup>
</Col>
</Row>
<Button>Add</Button>
</Form>
</Fragment>
);
};
export default SocialForm;
关于javascript - 提交时清除输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59521502/