【问题标题】:Error: Type '{ children: Element[]; }' has no properties in common with type 'IntrinsicAttributes & RefAttributes<HTMLFormElement>'错误:类型'{孩子:元素[]; }' 与类型 'IntrinsicAttributes & RefAttributes<HTMLFormElement>' 没有共同的属性
【发布时间】:2020-02-22 12:43:06
【问题描述】:

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

错误 TS2559 (TS) 类型 '{ children: Element[]; }' 中没有属性 与类型 '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>

【问题讨论】:

  • 在渲染函数中返回空表单是否可以正常工作?如果是,请尝试逐个添加 div 部分

标签: reactjs forms typescript formik


【解决方案1】:

这似乎是 formik v2(21 小时前发布)的问题,我在干净的 CRA 安装 formik 时遇到了同样的问题,它似乎遗漏了允许 &lt;Form /&gt; 生孩子的类型。

我建议现在降级到 v1.5.8,我可以确认这将解决您的问题。

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

【讨论】:

  • 是的,这是我今天安装的版本才遇到的问题。
【解决方案2】:

对于其他坚持这一点的人来说,至少从 Formik v2.0.11 以及可能更高版本开始,这似乎仍然是一个问题。

我的特殊问题是使用 withFormik HOC 和 Formik 的 &lt;Form&gt; 组件,例如:


    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 的官方示例:

并注意到,即使在示例中,他们也没有使用自己的 &lt;Form /&gt; 组件。解决方法是用标准的 html &lt;form&gt; 替换 &lt;Form /&gt; (并记住将 handleSubmit 属性传递给 &lt;form&gt;,这显然是 Formik 的 &lt;Form /&gt; 在这种情况下未能做到的):


    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;

【讨论】:

    猜你喜欢
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 2022-09-23
    • 2022-08-17
    • 2019-08-03
    相关资源
    最近更新 更多