当前位置: 首页 > 工具软件 > Material UI > 使用案例 >

React + material-ui + react-hook-form实现react表单控制

傅明知
2023-12-01

React + material-ui + react-hook-form实现react表单控制

CustomForm.jsx

import React from "react";
import { FormControl } from "@material-ui/core";
import { useForm } from "react-hook-form";
import { InputField, SelectField } from "./FormFields";

export default React.forwardRef((props, ref) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  React.useImperativeHandle(ref, () => ({
    handleSubmit,
  }));

  return (
    <form ref={ref}>
      <FormControl fullWidth>
        <InputField
          error={Boolean(errors.lastName)}
          {...register("lastName", { required: true })}
          error-text={"this item is requiredsss"}
        >
          Name
        </InputField>
      </FormControl>
      <FormControl fullWidth>
        <SelectField
          error={Boolean(errors.firstName)}
          {...register("firstName", { required: true })}
          error-text={"this item is required"}
        >
          First Name
        </SelectField>
      </FormControl>
    </form>
  );
});

FormFields.jsx

import {
  InputLabel,
  FormHelperText,
  Input,
  Select,
  MenuItem,
} from "@material-ui/core";
import { useState, forwardRef } from "react";

export const InputField = forwardRef((props, ref) => {
  return (
    <div style={{ height: 66 }} ref={ref}>
      <InputLabel
        required={props.required === false ? false : true}
        error={props.error}
      >
        {props.children}
      </InputLabel>
      <Input fullWidth {...props} />
      {props.error ? (
        <FormHelperText error={props.error} id="my-helper-text">
          {props["error-text"] || "this item is required"}
        </FormHelperText>
      ) : (
        " "
      )}
    </div>
  );
});

export const SelectField = forwardRef((props, ref) => {
  const [value, setValue] = useState("");

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const error = props.error && value === "";

  return (
    <div style={{ height: 66 }} ref={ref}>
      <InputLabel
        required={props.required === false ? false : true}
        error={error}
      >
        {props.children}
      </InputLabel>
      <Select
        {...props}
        error={error}
        fullWidth
        value={value}
        onChange={handleChange}
      >
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
      {error ? (
        <FormHelperText error={error} id="my-helper-text">
          {props["error-text"] || "this item is required"}
        </FormHelperText>
      ) : (
        " "
      )}
    </div>
  );
});

这里实例性地自定义了两种表单域格式Input和Select,这里用到了第三方库react-hook-form和react的api:useImperativeHandle和fowardRef,其中useImperativeHandle用来定义向父组件暴露哪些属性和方法。

 类似资料: