我正在尝试让useFormik验证单选组,但这似乎不起作用,这是我正在做的简短示例,每当我在检查任何单选输入后提交表单时,formik都会引发验证错误, ({currState:“您必须选择属性状态”}),即使我选择了一个选项。 我意识到getFieldProps会将value字段附加到无线电中,所以我尝试使用defaultValue,然后反应引发有关选择受控和不受控制的组件之一的错误。
import { useFormik } from "formik"
export function ListProperty(){
const { handleSubmit, getFieldProps, touched, errors } = useFormik(
{
initialValues: {
currState:"",
},
validationSchema:Yup.object().shape({
currState:Yup.string().required("you must choose property state")
}),
return (
<form onSubmit={handleSubmit} >
<div className="form-group inline">
<div className="form-control">
<input type="radio"
name="currState"
{...getFieldProps("currState")}
value="serviced"
/>
<label>serviced</label>
</div>
<div className="form-control">
<input
type="radio"
value="furnished"
name="currState"
{...getFieldProps("currState")}
/>
<label>furnished</label>
</div>
<div className="form-control">
<input
type="radio"
value="newlybuilt"
name="currState"
{...getFieldProps("currState")}
/>
<label>newly built</label>
</div>
</div>
<button type="submit">submit </button>
</form>
)
}
答案 0 :(得分:0)
您可以尝试通过这种方式进行操作。它应该工作。似乎getFieldProps(“ currState”)覆盖了值属性,但不提供已检查的属性。
import { useFormik } from "formik"
export function ListProperty(){
const { handleSubmit, getFieldProps, touched, errors,
values, handleChange } = useFormik({
initialValues: {
currState:"",
},
validationSchema:Yup.object().shape({
currState:Yup.string().required("you must choose property state")
}),
return (
<form onSubmit={handleSubmit} >
<div className="form-group inline">
<div className="form-control">
<input type="radio"
name="currState"
checked={values.currState === 'serviced'}
onChange={handleChange}
value="serviced"
/>
<label>serviced</label>
</div>
<div className="form-control">
<input
type="radio"
value="furnished"
name="currState"
checked={values.currState === 'furnished'}
onChange={handleChange}
/>
<label>furnished</label>
</div>
<div className="form-control">
<input
type="radio"
value="newlybuilt"
name="currState"
checked={values.currState === 'newlybuilt'}
onChange={handleChange}
/>
<label>newly built</label>
</div>
</div>
<button type="submit">submit </button>
</form>
)
}