我创建了一个小表格,用户可以在其中键入数字,然后按Enter键提交。
当前,我创建了一个隐藏的Button
,它具有onClick={handleSubmit}
和type="submit"
属性。
这给用户一种不存在该按钮的错觉。
一切正常。
如何
我认为创建Button
只是为了给它onClick
并将其隐藏起来是多余的。
我想知道是否还有其他方法可以创建表单而不创建按钮。
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>
)
}
答案 0 :(得分:1)
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>
)
}
尝试在onSubmit
上添加<Form/>
道具
答案 1 :(得分:1)
您可以尝试以下方法:
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>
)
}