【问题标题】:TypeError: React.createContext is not a function (Nextjs 13 & Formik with Typescript)TypeError: React.createContext 不是函数(Nextjs 13 & Formik with Typescript)
【发布时间】:2022-11-04 16:28:48
【问题描述】:

我现在正在尝试使用 Formik 在 NextJs 13 (Typescript) 上创建一个表单。我创建的表单不起作用,然后我尝试从Formik 添加示例代码 sn-ps,如下所示。我创建的表单和 Formik 的示例都只在控制台中返回 TypeError: React.createContext is not a function。我可以在另一行控制台错误中看到这个(sc_server)/./node_modules/formik/dist/formik.cjs.development.js

import * as React from 'react';
import {
  Formik,
  FormikHelpers,
  FormikProps,
  Form,
  Field,
  FieldProps,
} from 'formik';

interface MyFormValues {
  firstName: string;
}

export const MyApp: React.FC<{}> = () => {
  const initialValues: MyFormValues = { firstName: '' };
  return (
    <div>
      <h1>My Example</h1>
      <Formik
        initialValues={initialValues}
        onSubmit={(values, actions) => {
          console.log({ values, actions });
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
        }}
      >
        <Form>
          <label htmlFor="firstName">First Name</label>
          <Field id="firstName" name="firstName" placeholder="First Name" />
          <button type="submit">Submit</button>
        </Form>
      </Formik>
    </div>
  );
};

我在 /app/page.tsx 中导入了上述组件,如下所示。

import { MyApp } from '../components/form/MyApp';

export default function Home() {
  return (
    <div>
      <MyApp />
    </div>
  );
}

【问题讨论】:

    标签: reactjs typescript next.js formik


    【解决方案1】:

    我遇到了同样的错误,但使用的是 Material UI 的 DataTable。

    DataTable 使用 React Context API,此类 API 仅对客户端组件可用:https://beta.nextjs.org/docs/upgrade-guide#migrating-_documentjs-and-_appjs

    添加“使用客户端”;在页面顶部修复了我的错误。 Formik 可能就是这种情况。

    【讨论】:

    • 您好@WindWalker,我尝试在页面顶部添加“使用客户端”,但它只会引发相同的错误。现在,我只是将相关文件移动到 /pages 目录,它工作正常。一旦有解决方案,我可能会将它们移回 /the app 目录。
    【解决方案2】:

    在“MyApp 和“Home”组件的第一行使用“使用客户端”。因为 next13 使用客户端和服务器组件

    检查此链接https://beta.nextjs.org/docs/rendering/server-and-client-components

    【讨论】:

      猜你喜欢
      • 2023-01-14
      • 2021-08-04
      • 2022-12-01
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 2022-10-19
      • 2020-03-11
      相关资源
      最近更新 更多