Calling input click() from react ref does not work

时间:2018-07-24 10:15:38

标签: reactjs typescript input click refs

I want to trigger the HTML validation of a form field before submitting it (type email here). More precisely when losing focus. From what I gathered it's not possible to trigger the built-in validation without submitting the form, hence this 'hack'. I'm using react 16.4.1 and TypeScript.

Here is the code:

The constructor:

private submitRef: React.RefObject<HTMLInputElement>;
public constructor(props: IProps) {
    super(props);
    this.submitRef = React.createRef();
}

The render method:

 <form onSubmit={this.handleSubmit} name="login">
     <input
         className="input"
         id="email"
         name="login.email"
         value={this.state.login.email}
         onChange={this.handleChange}
         placeholder="Email"
         type="email"
         onBlur={this.checkEmailValidity}
         required={true}
     />
     <input type="submit" value="Login" ref={this.submitRef} />
 </form>

The checkEmailValidity method:

@autobind
private checkEmailValidity(event: React.FormEvent<HTMLInputElement>) {
    if (!event.currentTarget.checkValidity()) {
        this.submitRef.current!.click();
    }
}

So when losing focus, the checkEmailValidity method is called, and verifies that the input is indeed not valid. I checked that the reference to the current element is returning the correct input, but when calling click(), nothing happens. Am I doing something wrong here ?

Thanks.

Edit: calling focus() on the input is working though.

0 个答案:

没有答案