如何重定向文本字段,输入要提交表单而不是中途提交按钮的命令?

时间:2019-05-30 10:57:57

标签: javascript reactjs forms material-ui

我正在使用材质UI作为我的组件库。我有一个小对话框,该对话框在表单内的某个位置有一个“恢复密码”按钮。 -我注意到添加此按钮后,文本字段中的“输入”命令将成为按钮的onClick命令。

表格就像:

type PropTy = {
    classes: any,
    submit: (Event) => mixed;
    handleClose: (Event) => mixed;
    handleRequestPasswordRecover: (Event) => mixed;
};

function SigninForm(props:PropTy) {
    const {classes, submit, handleClose, handleRequestPasswordRecover} = props;
    const signinRef = React.createRef();

    const actions = [
        <Button
            type="reset"
            label="Reset"
            color="secondary"
            style={{ float: 'left' }}
            key='reset'
        >Reset</Button>,
        <Button
            label="Cancel"
            color="primary"
            onClick={handleClose}
            key='cancel'
        >Cancel</Button>,
        <Button
            type="submit"
            label="Submit"
            variant="contained"
            color="primary"
            key='submit'
            autoFocus
        >Login</Button>,
    ];


    return (
        <form className={classes.form}
              onSubmit={submit}
              ref={signinRef}
        >
            <FormControl margin="normal" required fullWidth>
                <TextField id="username" name="username" autoComplete="username" autoFocus label={'Username'}/>
            </FormControl>
            <FormControl margin="normal" required fullWidth>
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'baseline'}}>
                    <FormLabel htmlFor="password">Password</FormLabel>
                    <button className={classes.linkButton} onClick={(e) => {
                        handleRequestPasswordRecover(e)
                    }}>{'Lost password?'}</button>
                </div>
                <Input
                    name="password"
                    type="password"
                    id="password"
                    autoComplete="current-password"
                />
            </FormControl>
            <FormControlLabel
                control={<Checkbox value="remember" color="primary" />}
                label="Remember me"
            />
            <div style={{ textAlign: 'right'}}>
                {actions}
            </div>
        </form>);
}

在“ enter”上发生的动作不是我所期望的“ submit”-而是按钮的onClick事件(handleRequestPasswordRecover)。我该如何重定向?

3 个答案:

答案 0 :(得分:2)

您应将type的按钮的onClick={(e) => { handleRequestPasswordRecover(e)...属性设置为"button"(即<button type="button"...)。

按钮的默认类型为submit

答案 1 :(得分:0)

在内部提交功能中,您可以调用preventDefault();

  

const commit =(event)=> {event.preventDefault(); }

答案 2 :(得分:0)

您可以在 form 标签上的html中编写以下代码。因此,您可以防止在关注文本字段时按Enter键提交表单。

<form className={classes.form}
          onSubmit={submit}
          ref={signinRef}
          onKeyPress={(event) => {
                if (event.key === "Enter") {
                   event.preventDefault();
                }
          }}>