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

React-Admin 4.8.3 SelectInput重置后无焦点且不显示校验错误

React-Admin 4.8.3 SelectInput重置后校验错误不立即显示的解决方法

问题场景

使用以下代码创建带重置叉号的SelectInput:

<ReferenceInput
  label={label}
  reference={reference}
  sort={byTranslatedAscendingNameSort}
  source={source}
>
  <SelectInput
    optionText={`name_${locale}`}
    resettable={true}
    source="id"
    validate={required()}
  />
</ReferenceInput>

点击重置叉号后,字段值已被重置为undefined,且SelectInput和SimpleForm已生成对应错误对象,但校验错误不会立即展示,必须等组件获得焦点再失去后才会显示。

解决方案

通过自定义重置逻辑,结合React-Admin的表单上下文手动触发校验并让组件聚焦,具体实现如下:

  1. 封装自定义可重置SelectInput组件:
import { useFormContext, SelectInput } from 'react-admin';
import { useRef } from 'react';

const ResettableSelectInput = (props) => {
  const inputRef = useRef(null);
  const { form } = useFormContext();
  const { source, ...rest } = props;

  const handleReset = () => {
    // 重置字段值
    form.setValue(source, undefined);
    // 手动触发该字段的校验
    form.validateField(source);
    // 让组件获得焦点
    inputRef.current?.focus();
  };

  return (
    <SelectInput
      {...rest}
      source={source}
      ref={inputRef}
      resettable={false}
      resetIconProps={{ onClick: handleReset }}
    />
  );
};
  1. 在ReferenceInput中替换使用自定义组件:
<ReferenceInput
  label={label}
  reference={reference}
  sort={byTranslatedAscendingNameSort}
  source={source}
>
  <ResettableSelectInput
    optionText={`name_${locale}`}
    source="id"
    validate={required()}
  />
</ReferenceInput>

原理说明

  • 通过useFormContext获取表单实例,调用validateField方法直接触发字段校验,确保错误立即渲染
  • 利用ref获取组件DOM元素,重置后主动聚焦,贴合用户操作预期
  • 替换原生重置逻辑,避免原生仅修改值但不触发校验和聚焦的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:52:10