我有一个表单,它将数据提交给API,然后从那里提交到MySQL数据库。
该表单具有类型为switch
的Form.Check
。并且当接通时提供值CCD_ 3。但是,我已经将数据库设置为接受tinyint
——1或0。
有没有办法返回1而不是on
?对于下面的控制台输出,console.log(formData.favourite)
和console.log(formData.scheduled)
当前返回on
,或者根本不返回。
处理程序
const initialFormData = Object.freeze({
title: "",
summary: "",
wiki_source: "",
date: "",
scheduled: "",
favourite: "",
location_id: ""
});
const [formData, updateFormData] = React.useState(initialFormData);
const handleChange = (e) => {
updateFormData({
...formData,
// Trimming any whitespace
[e.target.name]: e.target.value.trim()
});
};
const handleSubmit = (e) => {
e.preventDefault()
console.log(formData.title);
console.log(formData.summary);
console.log(formData.wiki_source);
console.log(formData.date);
console.log(formData.scheduled);
console.log(formData.favourite);
console.log(formData.location_id);
}
莫代尔
<Modal show={isOpen} onHide={closeModal}>
<Modal.Header closeButton>
<Modal.Title>New Event</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Form.Group controlId="formTitle">
<Form.Label>Title:</Form.Label>
<Form.Control size="sm" type="text" name="title" placeholder="Title of event" onChange={handleChange}/>
<Form.Text className="text-muted">
The url of the source you are adding
</Form.Text>
</Form.Group>
<Form.Group controlId="formSummary">
<Form.Label>Summary</Form.Label>
<Form.Control size="sm" type="text" name="summary" placeholder="Summary" onChange={handleChange}/>
</Form.Group>
<Form.Group controlId="formWikiSource">
<Form.Label>Wiki Source</Form.Label>
<Form.Control size="sm" type="text" name="wiki_source" placeholder="Wiki Page URL" onChange={handleChange}/>
</Form.Group>
<Form.Group controlId="formDate">
<Form.Label>Date</Form.Label>
<Form.Control size="sm" type="date" name="date" onChange={handleChange}/>
</Form.Group>
<Form.Group controlId="formScheduled">
<Form.Check type="switch" name="scheduled" label="Set as a scheduled event" onChange={handleChange} />
</Form.Group>
<Form.Group controlId="formFavourite">
<Form.Check type="switch" name="favourite" label="Set as favourite" onChange={handleChange} />
</Form.Group>
</Form>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={handleSubmit}>
Submit
</Button>
</Modal.Footer>
</Modal>
我假设Form.Check
是input type="checkbox"
的包装器。如果是这样,并且假设它支持常见的value
属性,则可以使用value="1"
使复选框值为"1"
(字符串(,而不是"on"
。它仍然是一个字符串,尽管您可以将其转换为数字,例如:
updateFormData({
...formData,
// Trimming any whitespace
[e.target.name]: e.target.type === "checkbox" ? +e.target.value : e.target.value.trim()
});
或者直接查找"on"
:
updateFormData({
...formData,
// Trimming any whitespace
[e.target.name]: e.target.type === "checkbox" ? (e.target.value === "on" ? 1 : 0) : e.target.value.trim()
});