You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合Semantic UI与react-hook-form实现表单单输入项错误提示

实现方法
  • 删掉你手动编写的<p>错误提示标签,Semantic UI的error属性会自动渲染符合组件样式的错误提示
  • 给Form.Input组件的error属性做动态绑定:有对应校验错误时传入错误配置对象,无错误时传入false即可关闭错误状态,不会出现输入框一直红的问题
  • 针对不同的校验规则返回对应的错误提示文案即可

完整代码示例

import { useForm } from 'react-hook-form';
import { Form, Button } from 'semantic-ui-react';

function CatInfoForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();

  const submitHandler = (formData) => {
    // 处理表单提交逻辑
    console.log(formData);
  };

  // 根据错误类型返回对应提示
  const getNameErrorTip = () => {
    switch(errors.name.type) {
      case 'required':
        return "请填写猫咪的名字";
      case 'minLength':
        return "猫咪名字长度不能少于2位";
      case 'maxLength':
        return "猫咪名字长度不能超过30位";
      default:
        return "";
    }
  };

  return (
    <Form onSubmit={handleSubmit(submitHandler)}>
      <Form.Field>
        <Form.Input
          label="名字"
          placeholder="输入猫咪的名字"
          type="text"
          {...register("name", { required: true, minLength: 2, maxLength: 30 })}
          // 核心动态控制逻辑
          error={errors.name ? { content: getNameErrorTip(), pointing: 'below' } : false}
        />
      </Form.Field>
      <Button type="submit">提交</Button>
    </Form>
  );
}

react-hook-form默认校验触发时机为提交后,刚好符合你的需求:用户未提交时不会展示错误,只有提交后校验不通过才会触发输入框变红、展示对应错误提示的效果。

内容的提问来源于stack exchange,提问作者edesoares

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:15:03