reactjs - 将 Formik 与 React.FC 一起使用
问题描述
我有一个表单,它在 React 中设置为函数组件,其中表单值由状态挂钩管理。我想将 Formik 添加到此,但是当我设置增强表单时,我收到此错误:
Argument of Type FC<Props> is not assignable to parameter of type 'CompositeComponent<FormikSharedConfig & FormikState<{}> & FormikActions<{}> & FormikHandlers & FormikComputedProps<{}> & FormikRegistration>
该组件的设置类似于
const Form: React.FC<Props> = () => {
[formVal, setFormVal] = React.useState<string>('')
[formValTwo, setFormValTwo] = React.useState<string>('')
// some functions related to managing the form
return (
<>
// render form
</>
)
}
const EnhancedForm = withFormik ({
mapPropsToValues: () => ({...props})
handleSubmit:(values, {setSubmitting}) => {...}
})(EnhancedForm) // above error shows here
我用错了Formik吗?如果是这样,我将如何为 React.FC 进行表单管理?
解决方案
的价值是Props
多少?
在您的代码片段中,您为什么要这样做:
const EnhancedForm = withFormik ({
mapPropsToValues: () => ({...props})
handleSubmit:(values, {setSubmitting}) => {...}
})(EnhancedForm) // above error shows here
代替:
const EnhancedForm = withFormik ({
mapPropsToValues: () => ({...props})
handleSubmit:(values, {setSubmitting}) => {...}
})(Form) // above error shows here
也许你可以试试这个:
import { InjectedFormikProps } from 'formik';
interface FormValues {
// The values of your form
// email: string;
// password: string;
}
interface Props {
// your props
}
const Form: React.FC<InjectedFormikProps<Props, FormValues>> = () => {
[formVal, setFormVal] = React.useState<string>('')
[formValTwo, setFormValTwo] = React.useState<string>('')
// some functions related to managing the form
return (
<>
// render form
</>
)
}
const EnhancedForm = withFormik ({
mapPropsToValues: () => ({...props})
handleSubmit:(values, {setSubmitting}) => {...}
})(Form) // above error shows here
这样你就可以告诉 Typescript 你的Form
组件接受 Formik 相关的 props。因为 Typescript 无法知道这一点。
推荐阅读
- javascript - classList 对元素的更改仅在迭代期间存在
- swift - 如何创建字典扩展
- python - Python:尝试创建两个变量上下文管理器
- flutter - 如何在 Dart 中使用正则表达式拆分九个字符的字符串?
- java - 容器之间的连接问题(我想......)
- sql - 为什么 Tableau 不接受我的初始 SQL (Oracle)?
- drupal - 带有ajax提交按钮的表单中的Drupal 8批处理
- python - 如何正确安装 PyGObject?(OSX)
- javascript - 如何将本地 JS 文件中的数据附加到 ReactJS 中的状态?
- c# - “服务器违反了协议。Section=ResponseStatusLine” - 没有发送请求