how to disable <ENTER> key for form submit in react-bootstrap

☆樱花仙子☆ 提交于 2019-12-10 21:07:23

问题


In the following snippet, I have a number of input forms that are type text. If the user hits , it seems I am getting the same synthetic event as if they press the submit button. I want to ignore the as a form submit, and only allow one to press the SUBMIT button. (I deleted some of the Form Groups to cut down on the example).

In all cases (button or ENTER key)

e.key is undefined
e.which is undefined
e.type is submit
e.target is the submit button 

(this is a synthetic event)

const React = require('react')
import { Form, FormControl, FormGroup, ControlLabel, Col, Button, Tooltip, OverlayTrigger } from 'react-bootstrap'

const Configuration = ({ ServerPort, UserID, PortNumber, WWWUrl, SourcePath, FMEPath }) => {
    const buttonAction = (e) => {
        e.preventDefault();
        alert(e.target.innerHTML)
    }
    return (
        <Form horizontal>
            <FormGroup controlId="serverPortBox">
                <Col componentClass={ControlLabel} sm={2}>Watson Port:</Col>
                <Col sm={10}>
                    <OverlayTrigger placement="left" overlay={(<Tooltip id="tt1">TCP port for Watson to use</Tooltip>)}>
                        <FormControl type="number" min="1024" max="65535" placeholder={ServerPort} />
                    </OverlayTrigger>
                </Col>
            </FormGroup>
            <FormGroup controlId="dbPortBox">
                <Col componentClass={ControlLabel} sm={2}>Database Port:</Col>
                <Col sm={10}>
                    <OverlayTrigger placement="left" overlay={(<Tooltip id="tt3">TCP port for PostGreSql DB</Tooltip>)}>
                        <FormControl type="number" min="1024" max="65535" placeholder={PortNumber} />
                    </OverlayTrigger>
                </Col>
            </FormGroup>
            <Button type="submit" bsStyle="primary" block onClick={(e) => buttonAction(e)}>Update Configuration</Button>
        </Form>
    )
}

export default Configuration

回答1:


Maybe should insert button with type "button" instead "submit"? and then just handle onClick for this button?




回答2:


The easiest solution would be to just use type="button" instead of type="submit".




回答3:


I found solution how to implement this without using type="button"

const handleKeyDown = (event, callback) => {
  if (event.key === 'Enter' && event.shiftKey === false) {
    event.preventDefault();
    callback(submitAddress);
  }
};

and changes in form:

<form onSubmit={handleSubmit(submitAddress)} onKeyDown={e => { handleKeyDown(e, handleSubmit) }}>


来源:https://stackoverflow.com/questions/43767888/how-to-disable-enter-key-for-form-submit-in-react-bootstrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!