Formik 未在屏幕上呈现任何内容

时间:2021-07-07 03:59:24

标签: javascript reactjs typescript formik

我对 react 和 next.js 非常陌生,所以我一直在关注一个教程视频,该视频曾展示了如何使用 formik 创建注册屏幕。我基本上直接复制了视频,但是当我尝试渲染所有内容时,什么也没有出现。我知道代码消失是由于 formik 造成的,因为我将其删除并添加到一个简单的 div 中并进行渲染。这是我的代码以及我的 package.json:

不工作的页面:

import React from 'react';
import {Formik, Form} from "formik";
import {Wrapper} from "../components/Wrapper";
import {InputField} from "../components/InputField";
import {Box, Button} from "@chakra-ui/react";

interface registerProps {}

const Register : React.FC<registerProps> = ({}) => {
    return (
        <Wrapper>
            <Formik initialValues={{ email:"", password:""}} onSubmit={(values) => {console.log(values);}}>
                {() => ({}) => (
                    <Form>
                        <InputField name='email' label='Email'/>
                        <Box mt={4}>
                            <InputField name='password' label='Password'/>
                        </Box>
                        <Button mt={4} type="submit">Submit</Button>
                    </Form>
                )}
            </Formik>
        </Wrapper>
    );
}

export default Register;

注册屏幕的包装:

import React from "react";
import {Box} from "@chakra-ui/react";

interface WrapperProps {
    variant?: 'small' | 'regular';
}

export const Wrapper: React.FC<WrapperProps> = ({ children, variant = "regular"}) => {
    return (
        <Box
            mt={8}
            mx="auto"
            maxW={variant === "regular" ? "800px" : "400px"}
            w="100%">
            {children}
        </Box>
    );
};

输入字段:

import React, {InputHTMLAttributes} from "react";
import {useField} from "formik";
import {FormControl, FormErrorMessage, FormLabel, Input} from "@chakra-ui/react";

type InputFieldProps = InputHTMLAttributes<HTMLInputElement> & {
    label : string,
    name : string;
}

export const InputField: React.FC<InputFieldProps> = ({label, size: _, ...props}) => {
    const [field, {error}] = useField(props);
    return (
        <FormControl isInvalid={!!error}>
            <FormLabel htmlFor="name">{label}</FormLabel>
            <Input {...field} id={field.name} placeholder={field.name} />
            {error ? <FormErrorMessage>{error}</FormErrorMessage> : null}
        </FormControl>
    )
}

Package.JSON:

{
  "name": "with-chakra-ui",
  "version": "0.1.0",
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@chakra-ui/core": "^0.8.0",
    "@chakra-ui/icons": "^1.0.0",
    "@chakra-ui/react": "^1.6.4",
    "@emotion/react": "^11.4.0",
    "@emotion/styled": "^11.0.0",
    "@types/node": "^16.0.0",
    "emotion-theming": "^11.0.0",
    "formik": "^2.2.9",
    "framer-motion": "^4.0.3",
    "next": "^11.0.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "typescript": "^4.3.5"
  },
  "license": "MIT"
}

0 个答案:

没有答案