[英]Submit a react form without clicking a button - React Bootstrap
I created a small form where the user types a number and submits it by pressing the Enter key.我创建了一个小表单,用户在其中键入一个数字并按 Enter 键提交。
Currently, I created a hidden Button
which has the onClick={handleSubmit}
and type="submit"
properties.目前,我创建了一个具有
onClick={handleSubmit}
和type="submit"
属性的隐藏Button
。 This gives the user the illusion that the button does not exists.这给用户一种按钮不存在的错觉。 Everything works.
一切正常。
HOWEVER I think that the creation of the Button
just that I can give it the onClick
and the hide it, it is redundant.但是我认为
Button
的创建只是我可以给它onClick
并隐藏它,这是多余的。
I am wondering if there are other ways to submit a form without creating a button.我想知道是否有其他方法可以在不创建按钮的情况下提交表单。
function SingleInventoryChanger({single_inventory, single_date}) {
const [newInventory, setNewinventory] = React.useState([{single_inventory}]);
console.log(newInventory)
function handleChange(event) {
setNewinventory(event.target.value)
}
function handleSubmit(event){
event.preventDefault();
console.log(newInventory)
console.log(single_date)
}
return(
<div>
<Form>
<Form.Row>
<Col>
<Form.Control placeholder={single_inventory} onChange={handleChange} />
</Col>
</Form.Row>
<Button variant="secondary" type="submit" onClick={handleSubmit} > # I am referring to this button
</Button> # I am referring to this button
</Form>
</div>
)
}
function SingleInventoryChanger({single_inventory, single_date}) {
const [newInventory, setNewinventory] = React.useState([{single_inventory}]);
console.log(newInventory)
function handleChange(event) {
setNewinventory(event.target.value)
}
function handleSubmit(event){
event.preventDefault();
console.log(newInventory)
console.log(single_date)
}
return(
<div>
<Form onSubmit={handleSubmit}>
<Form.Row>
<Col>
<Form.Control placeholder={single_inventory} onChange={handleChange} />
</Col>
</Form.Row>
</Form>
</div>
)
}
Try to add onSubmit
props on <Form/>
尝试在
<Form/>
上添加onSubmit
道具
You can try this:你可以试试这个:
function SingleInventoryChanger({single_inventory, single_date}) {
const [newInventory, setNewinventory] = React.useState([{single_inventory}]);
const formRef = useRef(null)
console.log(newInventory)
function handleChange(event) {
setNewinventory(event.target.value)
}
function handleSubmit(event){
event.preventDefault();
console.log(newInventory)
console.log(single_date)
}
const handleKeyDown = (ev)=>{
if(ev.keyCode ===13){ // enter button
formRef.current.submit()
}
}
return(
<div onKeyDown={handleKeyDown}>
<Form ref={formRef} onSubmit={handleSubmit}>
<Form.Row>
<Col>
<Form.Control placeholder={single_inventory} onChange={handleChange} />
</Col>
</Form.Row>
</Form>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.