antd pro ProForm去除chrome自动填充不生效
chrome对表单会自动填充,特别对 username、password、email。相信chrome初衷是好的,但对开发制造了不少麻烦。
文章目录
前言
今天写一个新增用户的表单,有两个属性对chrome很敏感,它们是用户名(username
)、密码(passward
),很顺利在chrome上它表现了自己的独特性:这两个字段自动填充。下面一起看看问题及解决方案。
一、问题
1.1 使用 ProFormFields
中ProFormText
和 ProFormText.Password
实现表单
- 代码
<ModalForm
title="新增用户"
……
>
……
<ProFormText
label="用户名"
name="username"
rules={[{ required: true }]}
hasFeedback
tooltip="用于用户登录的名称,建议全引文加数字组成"
fieldProps={{ autoComplete: 'off' }}
></ProFormText>
<ProFormText.Password
label="密码"
name="password2"
rules={[{ required: true }]}
hasFeedback
allowClear
initialValue="123456"
tooltip="默认初始密码为:123456"
fieldProps={{ autoComplete: 'off' }}
/>
……
</ModalForm>
- 表现
可以看到页面渲染结束后,回显了该站点下的用户名和密码。打开控制台,我们会发现它报了如下错误。
[DOM] Found 2 elements with non-unique id #email: (More info: https://goo.gl/9p2vKq)
<input placeholder="请输入" id="email" type="text" class="ant-input" value>
<input placeholder="请输入" id="email" type="text" class="ant-input" value>
user:1 [DOM] Found 2 elements with non-unique id #name: (More info: https://goo.gl/9p2vKq)
<input placeholder="请输入" id="name" type="text" class="ant-input" value>
<input placeholder="请输入" id="name" type="text" class="ant-input" value>
user:1 [DOM] Found 2 elements with non-unique id #username: (More info: https://goo.gl/9p2vKq)
<input placeholder="请输入" id="username" type="text" class="ant-input" value>
<input autocomplete="off" placeholder="请输入" id="username" type="text" class="ant-input" value="admin">
二、解决方案
原因就不赘述了,解决方案就是给input增加autoComplete
属性,并给其设置合适的值。阻止自动填充有两种值:off
和 new-password
两种选择,off
使用在旧版浏览器上,new-password
使用在新版浏览器上。
从代码中可以发现设置的fieldProps={{ autoComplete: 'off' }}
根本没有生效。即使改成 fieldProps={{ autoComplete: 'new-password' }}
也不能生效。由此可以断定 ProFormFields
中ProFormText
和 ProFormText.Password
中设置的 autoComplete
不能生效。
因此我们尝试下面方式
- 代码
<Form.Item
label="用户名"
name="username"
rules={[{ required: true }]}
hasFeedback
tooltip="用于用户登录的名称,建议使用英文字母/数字组合"
>
<Input autoComplete="new-password" ></Input>
</Form.Item>
<Form.Item
label="密码"
name="password2"
rules={[{ required: true }]}
hasFeedback
initialValue="123456"
tooltip="默认初始密码为:123456"
>
<Input.Password autoComplete="new-password" ></Input.Password>
</Form.Item>
- 效果
可以看出,显示正确了。
但是那个表单重复的问题依然存在
总结
该文记录了采用Antd Pro
中ProFormText
和 ProFormText.Password
时autoComplete
不生效的问题,同时给出了解决方案。
文中提到对于不同版本的chrome浏览器,其值不一样,因此如果小伙伴们写的是一个开放性软件,就要注意处理浏览器版本问题,使其能赋予正确的值( off
或 new-password
)