![](/img/trans.png)
[英]Material-UI's TextField validation and onChange event handler don't seem to work as expected
[英]formik onchange event handler not populating material ui TEXTFIELD
你好,我正在做一個反應項目,目前正在處理身份驗證過程,我正在使用 material ui 和 formik 來驗證和處理輸入更改,但這里的問題是,我的 TextField 中的 onchange formik 處理程序如果不工作,為什么? 我該如何解決這個問題。 我使用兩個 formik 實例登錄 formik 並注冊 formik 這也是一種更好的方法嗎?
const loginformik=useFormik({
initialValues:{
// firstName:"",
// lastName:"",
email:"",
password:"",
},
onSubmit:(values=>console.log(values))
})
const registerformik=useFormik({
initialValues:{
firstName:"",
lastName:"",
email:"",
password:"",
},
onSubmit:(values=>console.log(values))
})
<form className="signup input-group" id="signup" ref={registerRef} onSubmit={registerformik.handleSubmit}>
<TextField
fullWidth sx={{ width:'100%', }}
// helperText="enter email"
id="email"
label="Email"
name="email"
type='email'
className="auth_input"
value={registerformik.values.email}
onChange={registerformik.handleChange}
/>
<TextField
fullWidth sx={{ width:'100%',marginTop:'5%', }}
// helperText="enter email"
id="firstName"
label="FirstName"
name="name"
type='text'
className="auth_input"
defaultValue={registerformik.values.firstName}
onChange={registerformik.handleChange}
/>
<TextField
fullWidth sx={{ width:'100%',marginTop:'5%' }}
// helperText="enter email"
id="lastName"
label="LastName"
// defaultValue=""
name="last_name"
type='text'
className="auth_input"
defaultValue={registerformik.values.lastName}
onChange={registerformik.handleChange}
/>
<TextField
fullWidth
sx={{ width:'100% ',marginTop:'5% ' }}
type='password'
// helperText="enter password"
id="password"
label="Password"
defaultValue=""
name="password"
className="auth_input"
value={registerformik.values.password}
onChange={registerformik.handleChange}
inputProps={{
endAdornment:(
<InputAdornment position="end">
<IconButton
aria-label="toggle password"
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
edge="end"
>
<VisibilityIcon />
{/* {showPassword ? <VisibilityIcon /> : <VisibilityOffIcon />} */}
</IconButton>
</InputAdornment>
),
}}
/>
<Button variant="contained" type='submit' color="success" sx={{ width:'30% ', marginTop:'3%' }}>
Sign up
</Button>
</form>
您只是在 textField 中使用了錯誤的name
屬性,名稱值必須與目標 formik 屬性的名稱相匹配:例如name="name"
變為name="firstName"
<TextField fullWidth sx={{ width: "100%", marginTop: "5%" }} // helperText="enter email" id="firstName" label="FirstName" name="firstName" type="text" className="auth_input" defaultValue={registerformik.values.firstName} onChange={registerformik.handleChange} />
對於您的 lastName 字段:
<TextField fullWidth sx={{ width: "100%", marginTop: "5%" }} // helperText="enter email" id="lastName" label="LastName" name="lastName" type="text" className="auth_input" defaultValue={registerformik.values.lastName} onChange={registerformik.handleChange} />
最后,是的,使用兩個不同的 formik 實例是個好主意,因為每個實例都服務於不同的需求或用例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.