在React中,自动完成Chrome值不会立即触发onChange事件。因此,在页面的初始加载期间,它会导致MUI TextField Label和实际值的冲突。如何解决此问题?
尝试了许多方法,InputLabelProps在Value上收缩也不起作用。https://stackoverflow.com/a/65070465/15435022
<StyledTextField
fullWidth
id="email"
label="Email"
size="medium"
value={emailAddress}
onChange={(e) => setEmailAddress(e.target.value)}
error={emailError}
InputLabelProps={{
shrink: emailAddress != null && emailAddress != "" ? true : false,
}}
helperText={emailError ? "Please enter a valid email" : "Required"}
/>
尝试这种解决方案也会出现问题:执行const theme = createTheme({
时
Github资源:https://github.com/mui/material-ui/issues/14427#issuecomment-466054906
2条答案
按热度按时间hpcdzsge1#
据我所知,这比我们希望的更痛苦的原因是因为它最初是作为一种安全功能,以防止通过自动完成密码被盗,但一旦Chrome(等)取消了限制,React的去重复机制就接管了。这里有一些比我将要建议的稍微更像黑客的工作区,但是你可以决定你喜欢哪一个。
要避开这个问题,您可以为每个
input
的onAnimationStart
事件添加一个处理程序,检查animationName
是否为"mui-auto-fill"
,然后检查input
是否有-webkit-autofill
pseudo class,以查看浏览器是否自动填充了该字段。您还需要处理"mui-auto-fill-cancel"
的情况,在这种情况下,表单是自动填充的,用户清除值(重置shrink
)。举例来说:
结果on load应显示为:
Updatewith cancel --允许用户在自动填充加载后清除表单字段,并重置标签:
makeAnimationStartHandler
作为一个函数,它接受React.useState()
setter作为参数,并返回一个实际执行工作的处理程序,因为您的示例有两个字段,我希望1)减少代码,2)如果需要,允许您单独处理每个字段的手动输入用例。示例:https://z3vxm7.csb.app/
工作代码沙箱:https://codesandbox.io/s/autofill-and-mui-label-shrink-z3vxm7?file=/Demo.tsx
zzwlnbp82#
谢谢史蒂夫。效果很好。我根据你的回答为我的项目写了一个组件: