本文共 2525 字,大约阅读时间需要 8 分钟。
react 表单自动提交
I stumbled upon an issue while working on a project I had a form built using React, and how browser autofill interacted with it.
我在一个项目中偶然发现了一个问题,该项目有一个使用React构建的表单,以及浏览器如何自动与其交互。
You know, when the browser puts your username/password automatically because you typed it already in the past?
您知道吗,因为您过去曾经输入过用户名/密码,浏览器会自动将其输入?
That’s autofill, and that’s the cause of my problem. In particular I replicated it on Chrome and Firefox, but any browser might run into this.
那是自动填充,这就是我的问题的原因。 特别是我在Chrome和Firefox上复制了它,但是任何浏览器都可能会遇到此问题。
The form was a usual and simple form built with the useState
hook.
该表单是使用useState
挂钩构建的通常且简单的表单。
Here’s an example email
field of the form:
这是表单的示例email
字段:
import { useState } from 'react'//...const [email, setEmail] = useState('')
setEmail(event.target.value)} />
When you type the email in there, the email
value is updated using setEmail
and I’ll have it available on the form submit event, so I can send it to the server.
当您在其中键入电子邮件时,该email
值将使用setEmail
更新,并且可以在表单提交事件中使用它,因此可以将其发送到服务器。
At some point I realized the browser was autofilling the email and password, but React didn’t recognize it!
在某个时候,我意识到浏览器正在自动填充电子邮件和密码,但是React无法识别!
Maybe because it fills the field before React is completely running, so it can’t possibly intercept that event.
也许是因为它在React完全运行之前就填充了该字段,所以它不可能拦截该事件。
I researched a bit and got lost into a land of browser inconsistencies and differences in how autofill works, so I had to create a simple workaround.
我进行了一些研究,迷失于浏览器的不一致之处以及自动填充方式的差异,因此我不得不创建一个简单的解决方法。
I did it using useRef
and useEffect
:
我使用useRef
和useEffect
:
import { useState, useEffect, useRef } from 'react'
I create a ref:
我创建一个参考:
const emailField = useRef(null)
and in the JSX I attach it to the input field:
并在JSX中将其附加到输入字段:
setEmail(event.target.value)} />
Then I added a piece of code that every 100ms looks up the value of the field, and calls setEmail()
to update it:
然后,我添加了一段代码,每100ms查找一次字段的值,并调用setEmail()
进行更新:
useEffect(() => { let interval = setInterval(() => { if (emailField.current) { setEmail(emailField.current.value) //do the same for all autofilled fields clearInterval(interval) } }, 100)})
It’s not ideal, it involves DOM manipulation which is something we should avoid when using a library like React, but it works around this issue.
这是不理想的,它涉及DOM操作,这在使用像React这样的库时应该避免,但是可以解决此问题。
What if there’s no autofill? This will simply wait until the first character is typed, and will stop the loop.
如果没有自动填充怎么办? 这将只等到输入第一个字符后停止循环。
翻译自:
react 表单自动提交
转载地址:http://immgb.baihongyu.com/