chakra-ui useForm 数组动态遍历FormControl组件 表单验证 TS react nextjs

import { 
  Box,
  Flex,
  Button,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Input,
  InputGroup,
  InputLeftElement,
  InputRightElement,
 } from "@chakra-ui/react";

import { useForm } from "react-hook-form";
import { ReactNode, useCallback, useEffect, useState } from "react";

type arrType = {
  arr: string[]
}

const ED = () => {
  const [arr, setArr] = useState<any>([''])
  const {
    register,
    handleSubmit,
    trigger,
    // watch,
    setValue,
    formState: { errors },
    getValues,
  } = useForm<arrType>({
    mode: "onBlur"
  });


  const formSubmitHandle = useCallback(
    async (v:any) => {
      debugger
    },  
    []
  );

  return (
  <Box>
    <form onSubmit={handleSubmit(formSubmitHandle)}> 
        {arr.map((item: string, index: number) => {
          return (
            <FormControl mt={'44px'} isInvalid={!!errors[`arr`]? !!errors[`arr`][index]: false} key={index}>
              <InputGroup h={'40px'} mt={'30px'}>
                <Input
                  placeholder="输入手机号"
                  w={"340px"}
                  h={"100%"}
                  backgroundColor={"#F9F9FD"}
                  border={"1px solid #DEE0E2"}
                  {...register(`arr.${index}`, {
                    required: "手机号码不能为空",
                    pattern: {
                      value: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/,
                      message: "手机号码格式错误,请重新输入",
                    },
                  })}
                  onChange={() => {
                    
                  }}
                ></Input>
              </InputGroup>
              <FormErrorMessage position={"absolute"} fontSize="xs">
                {!!errors[`arr`] && errors[`arr`][index] && errors[`arr`][index]?.message as ReactNode}
              </FormErrorMessage>
            </FormControl>
          )
        })}
   
       <Button
          type="submit"
          mt={"40px"}
          w={"340px"}
          h={"40px"}
          background={'#2753FF'}
          borderRadius={"20px"}
        >
          提交
        </Button>
    </form>
  </Box>
  )
}

export default ED;

你可能感兴趣的:(react.js,ui,javascript)