我试图在提交表单后让单选按钮显示在控制台上,但即使选择了一个选项,我也会收到显示错误消息,并且我不确定我做错了什么。
这是formik实现
const SignupSchema = Yup.object().shape({
account: Yup.string().required('You must select an option'),
});
<Formik
initialValues={{
account: '',
}}
validationSchema={SignupSchema}
// on submit handles here
onSubmit={(values) => {
// same shape as initial values
console.log(values);
window.location.replace('/SelectProfileType');
}}
>
{({ errors, touched, formik }) => (
<Form>
{/* focus form error added here*/}
<ConnectedFocusError />
<FormControl>
<RadioGroup
aria-labelledby='demo-controlled-radio-buttons-group'
name='account'
value={value}
onChange={handleChange}
>
<FormControlLabel
value='artist'
name='account'
control={<Radio />}
/>
<br />
<FormControlLabel
value='golpher'
name='account'
control={<Radio />}
/>
<br />
<FormControlLabel name='account' control={<Radio />} />
</RadioGroup>
<ErrorMessage name='account' />
</FormControl>
<Button type='submit' variant='contained'>
Sign Up
</Button>
</Form>
)}
</Formik>
我在这里做错了什么?
添加一些额外的代码并调整当前的基础后,我能够解决我的问题。这是现在有效的代码。我添加了一个 on Change 处理程序,它帮助跟踪单选按钮的更改,这显然以前没有做过。现在,如果我尝试在不选择选项的情况下提交表单,无线电处理程序将弹出错误消息,直到选择选项为止。
const SignupSchema = Yup.object().shape({
account: Yup.string().required('please pick oe of three options'),
}
);
const [value, setValue] = React.useState('');
const [error, setError] = React.useState(false);
const [helperText, setHelperText] = React.useState('Please Choose Whichever Applies');
const handleRadioChange = (event) => {
setValue(event.target.value);
setHelperText(' ');
setError(false);
};
const handleSubmit = (event) => {
event.preventDefault();
if (value === 'artist') {
setHelperText('You selected artist!');
setError(false);
window.location.replace('http://localhost:3000/Signup');
} else if (value === 'golpher')
{
setHelperText('selected golpher');
setError(true);
}
};
const handleSubmit = (event) => {
event.preventDefault();
if (value === 'artist') {
setHelperText('artist selected!');
// send data to back end here
setError(false);
} else if (value === 'gallerist') {
setHelperText('Gallarist selected');
// send data to back end here
setError(true);
}
else if (value === 'collector') {
setHelperText('collector selected');
// send data to back end here
setError(true);
// show error here if the field is empty
} else {
setHelperText('Please select an option.');
setError(true);
}
};