React how to trigger form submit on input blur?

陌路散爱 提交于 2019-12-11 17:23:47

问题


I'm trying to make use of the HTML5 <input type="email" /> validation check.

I can get it working fine doing this:

<form>
  <input type="email" />
  <input type="submit" />
</form>

This gets the validation to work on clicking the sumbit button. However I'd like to trigger the form to submit upon having my email field blur.

How do I trigger the form without a submit button onBlur?

Like this:

<form>
  <input type="email" onBlur={/* trigger form submission */} />
</form>

Alternatively, is there a better approach to performaning the HTML5 email validation check upon input blur?


回答1:


Put a ref attribute on your form and call the submit function:

<form ref="myForm">
  <input type="email" onBlur={this.submitForm.bind(this)} />
</form>

Add a function:

submitForm(){
  this.refs['myForm'].submit()
}



回答2:


use the native checkValidity method

<form>
  <input type="email" id="a" />
</form>

const a = document.querySelector('#a')


a.addEventListener('blur', e => {
const isValid =  e.target.checkValidity()
console.log(isValid)
})


来源:https://stackoverflow.com/questions/52665541/react-how-to-trigger-form-submit-on-input-blur

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