reactjs - 打字稿 | Typescript 在 IProps 上扩展 formikProps 时缺少 27 个 Props
问题描述
我正在将 Formik 与 TypeScript 一起使用,并且我想在 TS 中使用一个非常简单的表单组件,在另一个组件中,我从中获取defaultValues
和validationSchemas
.
棘手的部分是如何只访问所需的 formikProps,而不会出现以下错误:
Type '{}' is missing the following properties from type 'Readonly<IProps>': values, errors, touched, isValidating, and 25 more.ts(2740)
(alias) class PasswordFields
import PasswordFields
这是组件的代码:
interface IProps extends FormikProps<IValues> {
username?: string;
email?: string;
}
interface IValues {
username?: string;
email?: string;
}
在主要组件中,我这样称呼它:
render(): ReactNode {
const { mode } = this.props;
return (
<Formik
initialValues={this.getInitialValues()}
validationSchema={this.getValidationSchemas()}
onSubmit={this.handleSubmit}
validateOnBlur={false}
render={({ isSubmitting, status }) =>
(
<Form>
{mode === ActionMode.EDIT_INFO && (
<Fragment>
<InfoFields /> // I am getting the error here..
<GroupSelectField />
</Fragment>
)}
<Button
className="btn btn-primary w-100 mt-5"
disabled={isSubmitting}
loading={isSubmitting}
type="submit"
>
{mode === ActionMode.EDIT_INFO && <span>UPDATE INFO</span>}
</Button>
</Form>
) as ReactNode
}
/>
);
}
我对此很感兴趣。你能告诉我如何只访问我想要的formikProps,所以TS,不会抱怨。?我还有另一个问题。如何将 props 从组件传递到 formik 表单。
解决方案
与您的其他具有相同问题的问题一样,InfoFields
期待您没有传入的道具:
<Formik
render={formikProps => (
<Form>
// Other Code.
<InfoFields {...formikProps} />
// Other Code.
</Form>
)}
/>
你能告诉我如何只访问我想要的 formikProps,所以 TS 不会抱怨
而不是上面的,你可以选择你真正想要的道具FormikProps
并将它们传递给InfoFields
. 例如这样的:
const InfoFields = ({ errors, touched }: Pick<FormikProps<IValues>, 'errors' | 'touched'>) => (
<div>
// Whatever.
</div>
);
...并在父组件中呈现:
<Formik
render={({ errors, touched }) => (
<Form>
// Other Code.
<InfoFields errors={errors} touched={touched} />
// Other Code.
</Form>
)}
/>
推荐阅读
- c++ - 如何避免参数数量取决于条件的调用分支?
- javascript - JavaScript:此事件侦听器调用的函数侦听器与预期不符
- authentication - 带有用户名和密码的 Openvpn
- asp.net-core - 如何在新用户注册时修复 EntityValidationError?
- c++ - RGB转XYZ,图像转换
- tensorflow - TF 2.0 Alpha 和 TF nightly preview 有什么区别?
- python - 如何在短时间内更改变量的值?
- android - 如何检测 NestedScrollView 的哪个滚动子项被滚动?
- c++ - 如何生成一个伪随机 32 字节字符串以用作加密哈希函数中的盐?
- r - R函数镜像COUNTIFS产生错误结果