Error: Type '{ children: Element[]; }' has no properties in common with type 'IntrinsicAttributes & RefAttributes<HTMLFormElement>'

Error: Type '{ children: Element[]; }' has no properties in common with type 'IntrinsicAttributes & RefAttributes<HTMLFormElement>'

我正在尝试在我的 React 应用程序中使用 Formik。我有用 ts 编写的登录组件。由于某种原因,Formik 中的 Form 元素抛出以下错误:

Error TS2559 (TS) Type '{ children: Element[]; }' has no properties in common with type 'IntrinsicAttributes & RefAttributes'.

我想知道如何缓解这个问题。有什么解决办法吗?

 <div>
            <Form></Form> // NO ERROR
            <h4>Login</h4>
            <Formik
                initialValues={{
                    username: '',
                    password: ''
                }}
                validationSchema={Yup.object().shape({
                    username: Yup.string().required('Username is required'),
                    password: Yup.string().required('Password is required')
                })}
                onSubmit={({ username, password }, { setStatus, setSubmitting }) => {
                    setStatus();
                    authenticationService.login(username, password)
                        .then(
                            result => {
                                console.log(result);
                                console.log(typeof result);

                                if (result.status == '500') {
                                    setSubmitting(false);
                                    setStatus("Login failed.");

                                } else if (result.status == '200') {
                                    if (result.data["roles"].result.includes('Admin'))
                                        history.push('/admin/courses');

                                    history.push('/courses');
                                }
                            },
                            error => {
                                setSubmitting(false);
                                setStatus(error);
                            }
                        );
                }}
                render={({ errors, status, touched, isSubmitting }) => (
                    <Form> // ERROR!!!
                        <div className="form-group">
                            <label htmlFor="username">Username</label>
                            <Field name="username" type="text" className={'form-control' + (errors.username && touched.username ? ' is-invalid' : '')} />
                            <ErrorMessage name="username" component="div" className="invalid-feedback" />
                        </div>
                        <div className="form-group">
                            <label htmlFor="password">Password</label>
                            <Field name="password" type="password" className={'form-control' + (errors.password && touched.password ? ' is-invalid' : '')} />
                            <ErrorMessage name="password" component="div" className="invalid-feedback" />
                        </div>
                        <div className="form-group">
                            <button type="submit" className="btn btn-primary" disabled={isSubmitting}>Login</button>
                            {isSubmitting && <LoadingSpinner />}
                        </div>
                        {
                            status &&
                            <div className={'alert alert-danger'}>Login failed.</div>
                        }
                    </Form>
                )}
            />

            />

        </div>

这似乎是 formik v2(21 小时前发布)的问题,我在干净的 CRA 安装 formik 时遇到了同样的问题,它似乎遗漏了允许 <Form /> 拥有的类型children.

我建议暂时降级到 v1.5.8,我可以确认这会解决您的问题。

当使用 formik 时,我还建议传入值类型,这些可以很容易地提供很多类型安全。您可以将 type Values = { username: string, password: string } 添加到文件顶部并将其传递到 Formik 组件,例如 <Formik<Values>

对于其他坚持这个的人来说,这似乎仍然是一个问题,至少在 Formik v2.0.11 和可能更高版本中。

我的特殊问题是将 withFormik HOC 与 Formik 的 <Form> 组件一起使用,例如:


    const MyForm = (props: Props) => {
        const { things, from, the, hoc } = props;
        // some logic
        return (
            <Form>
              <MyCustomFormElements /> 
            </Form
        );
    }
    
    const FormikForm = withFormik({
      mapPropsToValues: (props: OwnProps): OwnForm => {
        return {
          some: 'custom',
          values: 'and things'
        };
      },
      handleSubmit: (values, { props, setSubmitting }) => {
        props.handleSubmit(values, setSubmitting);
      },
      enableReinitialize: true,
      validateOnBlur: true,
      validateOnChange: true,
      validationSchema: (props: OwnProps) => formSchema(props.t),
    })(MyForm);
    
    export default FormikForm;

我在这里查看了 withFormik HOC 的官方示例:

并注意到,即使在示例中,他们也没有使用自己的 <Form /> 组件。修复方法是像这样用标准 html <form> 替换 <Form />(并记住将 handleSubmit 道具传递给 <form>,这显然是 Formik 的 <Form />在这种情况下未能做到):


    const MyForm = (props: Props) => {
        // notice the explicit use of handleSubmit!!
        const { things, from, the, hoc, handleSubmit } = props;
        // some logic
        return (
            <form onSubmit={handleSubmit}>
              <MyCustomFormElements /> 
            </form>
        );
    }
    
    const FormikForm = withFormik({
      mapPropsToValues: (props: OwnProps): OwnForm => {
        return {
          some: 'custom',
          values: 'and things'
        };
      },
      handleSubmit: (values, { props, setSubmitting }) => {
        props.handleSubmit(values, setSubmitting);
      },
      enableReinitialize: true,
      validateOnBlur: true,
      validateOnChange: true,
      validationSchema: (props: OwnProps) => formSchema(props.t),
    })(MyForm);
    
    export default FormikForm;