React Hook Form中Checkbox与File输入事件冲突问题咨询
问题分析与解决方案
结论
这不是React Hook Form的bug,是你的布局实现有误。
问题原因
你将file类型输入框设置为opacity-0 absolute,但未给它添加合理的定位约束:
- 绝对定位元素默认脱离文档流,若没有父级
relative容器限制,其位置和尺寸会不受控,极易溢出到相邻单元格区域。 - 点击checkbox时,实际触发的是覆盖在它上方的透明
file输入框,因此弹出了文件选择窗口。 - 之前用
text类型输入框无此问题,是因为text输入框点击不会触发弹窗,布局问题被隐藏了。
修复方案
给file输入框添加父级相对定位容器,限制它仅覆盖上传按钮区域:
<Controller control={control} name={`PSSE_File.${index}.path_to_dll_folder` as const} render={({ field: { value, onChange, ...field } }) => { return ( {/* 添加relative容器,约束内部绝对定位元素 */} <div className="relative"> <input type="file" {...field} onChange={(event) => { onChange(event.target.files && event.target.files[0].name) }} {/* 修改className,让输入框填满父容器,仅覆盖上传按钮区域 */} className="opacity-0 absolute inset-0 w-full h-full cursor-pointer" disabled={ PSSE_File_Info_Is_Submitted || methods.formState.isSubmitting } /> <div className="w-32 truncate"> {value ? ( <div className="border rounded outline-none px-2 py-2"> {value} </div> ) : ( <div className="flex items-center justify-center space-x-2 w-full cursor-pointer border rounded outline-none h-10"> <div> <icons.AiOutlineCloudUpload /> </div> <h2>Upload</h2> </div> )} </div> </div> ) }} />
修复原理
- 父容器设置
relative后,内部的absolute元素会以此容器为定位基准。 inset-0让file输入框的上下左右贴紧父容器,尺寸与父容器完全一致,只会覆盖上传按钮区域,不会溢出到旁边的checkbox单元格。
内容的提问来源于stack exchange,提问作者Sethumadhavan
相关产品推荐
相关产品推荐

