我有一个现有的表单,使用在 formik-material-ui 1.0 下工作的自定义组件:
const MyCheckbox = ({ field, form, label, ...rest }) => {
const { name, value: formikValue } = field
const { setFieldValue } = form
const handleChange = event => {
const values = formikValue || []
const index = values.indexOf(rest.value)
if (index === -1) {
values.push(rest.value)
} else {
values.splice(index, 1)
}
setFieldValue(name, values)
}
return (
<label>
<Checkbox onChange={handleChange} checked={formikValue.indexOf(rest.value) !== -1} {...rest} />
<span>{label}</span>
</label>
)
}
并使用此行进行渲染:
<Field component={MyCheckbox} name="sectionChoices" value={label} label={label} />
如文档所述,我删除了Field
导入和component
属性,但其余部分让我卡住了。如果 Field 不再可用,我应该在MyCheckbox
? 我试过了:
import { Formik, Form, useForm } from 'formik'
const MyCheckbox = ({ field, label, ...rest }) => {
const { name, value: formikValue } = field
const form = useForm()
const { setFieldValue } = form
const handleChange = event => {
const values = formikValue || []
const index = values.indexOf(rest.value)
if (index === -1) {
values.push(rest.value)
} else {
values.splice(index, 1)
}
setFieldValue(name, values)
}
return (
<label>
<Checkbox onChange={handleChange} checked={formikValue.indexOf(rest.value) !== -1} {...rest} />
<span>{label}</span>
</label>
)
}
但我得到这个错误:
Attempted import error: 'useForm' is not exported from 'formik'.
我的package.json
文件具有以下相关依赖项:
{
"dependencies": {
"@material-ui/core": "^4.5.1",
"@material-ui/icons": "^4.5.1",
"formik": "^2.0.3",
"formik-material-ui": "^2.0.0-alpha.3",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"react-router-dom": "^5.1.2",
"react-scripts": "3.3.1",
"recompose": "^0.30.0",
"typeface-roboto": "^0.0.75",
"yup": "^0.28.1"
},
...
}
迁移说明:
如前所述,我使用了此处的迁移说明,我还从中添加了一个屏幕截图。