我有单选按钮:A、B 和 C。
在按钮 B 下,有一个选择框,我想仅在选择 B 时才将此选择框设置为“必需”。
这是简化的代码:
interface ButtonFormType {
notificationType: "A" | "B" | "C";
selectedId?: string;
}
const {
register,
handleSubmit,
getValues,
watch,
formState: { errors },
} = useForm<ButtonFormType>();
.
.
.
return(
<form onSubmit={submit}>
<RadioGroup defaultValue={getValues("buttonType")}>
<VStack>
<Radio {...register("buttonType")} value={"A"}> Button A </Radio>
<Radio {...register("buttonType")} value={"B"}> Button B </Radio>
<FormControl isInvalid={!!errors[`selectedId`]}>
<Select
placeholder={"select"}
{...register("selectedId", {
required:
getValues("buttonType") === "B"
? "please select id"
: false,
})}
>
{idList.map(({ id, title }) => {
return (
<option key={id} value={id}>
{title}
</option>
);
})}
</Select>
</FormControl>
<Radio {...register("buttonType")} value={"C"}> Button C </Radio>
</VStack>
</RadioGroup>
<HStack marginY="40px" spacing={4}>
<Button type="submit"> Submit </Button>
</HStack>
</form>
)
当我选择按钮 B(不从选择框中选择任何内容)并点击提交按钮时, 它不会给我任何错误。
如果我再次点击提交按钮,则会出现错误消息。
我检查发现,当我更改buttonType时,
getValues("buttonType")
并没有更新。
点击提交按钮后就会更新。为什么?
我可以通过将
getValues
更改为 watch
来解决这个问题
required:
watch("buttonType") === "B"
? "please select id"
: false,
但仍然不明白为什么 getValues 不起作用。 有谁知道吗