首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用TextField -hook-form检查两个react-hook-form具有相同的值

,可以通过以下步骤来实现:

  1. 导入所需的库和组件:
代码语言:txt
复制
import React from "react";
import { useForm, Controller } from "react-hook-form";
import { TextField } from "@material-ui/core";
  1. 创建一个React函数组件并初始化react-hook-form:
代码语言:txt
复制
const MyForm = () => {
  const { control, handleSubmit, watch } = useForm();
  const onSubmit = (data) => {
    console.log(data);
  };
  
  const password = watch("password", ""); // 监听password字段的值,默认为空字符串
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="password"
        control={control}
        rules={{ required: true }}
        render={({ field }) => (
          <TextField {...field} label="Password" type="password" />
        )}
      />
      <Controller
        name="confirmPassword"
        control={control}
        rules={{ required: true, validate: (value) => value === password }}
        render={({ field }) => (
          <TextField {...field} label="Confirm Password" type="password" />
        )}
      />
      <button type="submit">Submit</button>
    </form>
  );
};
  1. 在表单中,我们使用了两个TextField组件,分别对应"password"和"confirmPassword"字段。在"confirmPassword"字段的规则中,我们使用了自定义的验证规则validate: (value) => value === password,用于判断"confirmPassword"字段的值是否与"password"字段的值相同。
  2. 在实际的使用中,你可以根据需要对这些字段进行扩展,例如添加错误提示、样式等。

请注意,上述代码中的腾讯云产品和产品介绍链接地址是虚构的,仅供参考。实际使用时,请根据实际情况替换为相应的产品和链接地址。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券