如何用ShadCN和React-Hook-Form实现复选框触发输入框并传值?
实现ShadCN + React-Hook-Form动态输入框(勾选Others时显示)
核心思路
通过React状态跟踪"Others"复选框的选中状态,结合React-Hook-Form的表单注册能力,动态渲染ShadCN输入框并绑定字段值。
1. 基础配置与状态管理
首先定义表单值类型,用useState控制输入框显示状态,同时初始化React-Hook-Form:
import { useState, useEffect } from "react"; import { useForm } from "react-hook-form"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; // 你的提供方选项数组 const items = [ { id: "tcet", label: "TCET" }, { id: "others", label: "Others" }, ] as const; // 定义表单值类型 type FormValues = { providers: string[]; // 存储选中的提供方ID otherProvider?: string; // 存储自定义提供方名称 }; export function ProviderForm() { const [showOtherInput, setShowOtherInput] = useState(false); const { register, handleSubmit, watch, formState: { errors } } = useForm<FormValues>({ defaultValues: { providers: [], otherProvider: "" } }); // 监听选中的提供方,自动切换输入框显示状态 const selectedProviders = watch("providers"); useEffect(() => { setShowOtherInput(selectedProviders.includes("others")); }, [selectedProviders]);
2. 渲染复选框组
用ShadCN的Checkbox组件循环渲染选项,直接通过register绑定表单字段:
return ( <form onSubmit={handleSubmit((data) => { // 提交时处理表单数据,示例:如果选中others,合并自定义值 const finalProviders = data.providers.map(id => id === "others" ? data.otherProvider : id ); console.log("最终提交数据:", finalProviders); })}> <div className="space-y-4"> <div className="space-y-2"> {items.map((item) => ( <div key={item.id} className="flex items-center space-x-2"> <Checkbox id={item.id} {...register("providers", { required: "请至少选择一个提供方" })} value={item.id} /> <label htmlFor={item.id} className="text-sm font-medium"> {item.label} </label> </div> ))} </div>
3. 动态渲染自定义输入框
当showOtherInput为true时,渲染ShadCN的Input组件,并添加条件必填验证:
{/* 动态显示Others输入框 */} {showOtherInput && ( <div className="space-y-2"> <label htmlFor="otherProvider" className="text-sm font-medium"> 请输入其他技术协助提供方 </label> <Input id="otherProvider" placeholder="输入提供方名称" {...register("otherProvider", { required: showOtherInput ? "此字段为必填项" : undefined })} /> {errors.otherProvider && ( <p className="text-red-500 text-xs">{errors.otherProvider.message}</p> )} </div> )} <button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-md"> 提交 </button> </div> </form> ); }
关键细节
- 用
watch监听表单字段变化,替代手动绑定复选框onChange,更贴合React-Hook-Form的数据流逻辑 - ShadCN组件直接通过
{...register(...)}绑定表单属性,和原生输入框用法完全一致 - 给自定义输入框添加条件必填,仅当"Others"被勾选时触发验证
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

