javascript - 如何让 Formik 检测 Checkbox 字段何时被选中?
问题描述
我正在制作一个需要验证的Checkbox 组件Yup
(使用 完成)。但它不会从复选框中检索实际值,而只是从 inside 中检索initialValues
。
表格代码:
<div className='metro custom-pg'>
<ThemeContext.Provider theme={theme}>
<Formik
initialValues={{
text: '',
email: '',
phone: '',
select: '',
multi: [],
checkbox: false,
}}
validationSchema={Schema}
onSubmit={(values) => {
alert(JSON.stringify(values, null, 2));
console.log("values", values);
}}
>
{({
errors,
values,
touched,
handleSubmit,
setFieldValue,
setFieldTouched,
}) => (
<Form onSubmit={handleSubmit}>
<Field
id='text-field'
label='Plain text'
name='text'
type='text'
placeholder='Enter some characters'
component={TextField}
/>
<Field
id='email-field'
label='Email'
name='email'
type='email'
placeholder='Enter your email'
component={TextField}
/>
<Field
id='phone-email'
label='Phone'
name='phone'
type='phone'
placeholder='Enter your phone'
component={TextField}
/>
<Field
id='select'
name='select'
name='select'
label='Select an option'
options={options}
component={Select}
/>
<MultiSelect
id='multiselect'
name='multi'
label='Select multiple options'
options={multiOptions}
value={values.multi}
onChange={setFieldValue}
onBlur={setFieldTouched}
touched={touched.multi}
error={errors.multi}
/>
<Field
type="checkbox"
name='check'
id='check'
label='Check the mark'
component={Checkbox}
/>
<Button variant="primary" type="submit">Submit</Button>
</Form>
)}
</Formik>
</ThemeContext.Provider>
</div>
复选框代码:
// @flow
import * as React from "react";
import { Field, ErrorMessage } from 'formik';
import { FormGroup, FormLabel } from "react-bootstrap";
export type Props = {
label?: String,
id?: String,
name?: String,
disabled?: boolean,
onChange: function,
className?: string
};
export const Checkbox = ({ label, disabled, id, className }: Props) => {
return (
<FormGroup>
<input type="checkbox" id={name} name={name} />
<label htmlFor={name}> {label}</label>
<ErrorMessage component="div" className="input-error" name="checkbox" />
</FormGroup>
);
};
Checkbox.defaultProps = {
label: 'Default text',
name: 'checkbox',
disabled: false,
className: ''
}
export default Checkbox;
解决方案
为了补充 Adrian Naranjo 的回答,您正在复选框上实现 Formik 的“onChange”回调。
<Formik
initialValues={{ ... }}
validationSchema={Schema}
onSubmit={(values) => { ... }}
>
{
({ handleChange, ...rest } => {
您需要将其传递handleChange
给您的Checkbox
组件。
Formik 的Field
组件将使onChange
回调可用,然后您可以将其传递给<input type="checkbox" />
.
推荐阅读
- javascript - jquery会自动将rgba转换为rgb吗?
- android - 停止服务如何影响服务中创建的线程?
- php - 计算shopify购物车页面中比较价格和小计之间的差异
- kubernetes - 在 kubernetes yaml 文件中为 OrientDb 指定 java 堆选项
- python - 使用 scrapy 抓取 Walmart.com 并获取“错误页面无法连接到服务器”
- sql - 为用户选择下次登录时间
- perl - Tesseract 无法识别 png 文件中的验证码,该文件包含英文字母的数字和字母
- javascript - 从输入类型“文件”获取文件并使用 jquery 移动到特定文件夹(不使用表单标签和提交按钮)
- facebook - 将 Cordova 原生 Facebook 插件用于 Ionic 应用程序和 DRF 服务器与 python-social-auth
- javascript - 添加异步等待而无需修改父调用函数