gpt4 book ai didi

javascript - 需要 React Hook Form 动态

转载 作者:行者123 更新时间:2023-12-04 11:32:48 25 4
gpt4 key购买 nike

我正在尝试使用 react 钩子(Hook)表单制作一个包含两个字段的表单,其中文本字段的所需值取决于选择下拉列表的值。
这是我的代码:

  const { handleSubmit, control, errors } = useForm();

const [isPickupPoint, togglePickupPoint] = useState(false);

const handleDestinationTypeChange: EventFunction = ([selected]) => {
togglePickupPoint(selected.value === "PICKUP_POINT");
return selected;
};

            <Grid item xs={6}>
<InputLabel>Destination type</InputLabel>
<Controller
as={Select}
name="destinationType"
control={control}
options={[
{ label: "Pickup point", value: "PICKUP_POINT" },
{ label: "Shop", value: "SHOP" },
]}
rules={{ required: true }}
onChange={handleDestinationTypeChange}
/>
{errors.destinationType && (
<ErrorLabel>This field is required</ErrorLabel>
)}
</Grid>
<Grid item xs={6}>
<Controller
as={
<TextField
label="Pickup Point ID"
fullWidth={true}
disabled={!isPickupPoint}
/>
}
control={control}
name="pickupPointId"
rules={{ required: isPickupPoint }}
/>
{errors.pickupPointId && (
<ErrorLabel>This field is required</ErrorLabel>
)}
</Grid>
<Grid item xs={12}>
<Button
onClick={onSubmit}
variant={"contained"}
color={"primary"}
type="submit"
>
Save
</Button>
</Grid>
isPickupPoint标志正确更改,因为 disabled textfield 的 Prop 工作正常。 Only when the PICKUP_POINT option is selected the text field is active.但是所需的 Prop 不起作用,它总是错误的。当我尝试在表单为空时提交表单时, destinationType出现错误标签,但是当我尝试使用 PICKUP_POINT 选项提交表单并清空 pickupPointId 时它通过的字段没有错误。
我怎样才能使这个动态所需的 Prop 工作?

最佳答案

根据这里的代码,它看起来像 isPickUpPoint正在按预期工作,因为它适用于禁用。由于您对 required 使用相同的属性,因此它应该流过。我怀疑该错误可能存在于您的Controller 中。零件。我会去那里看看,并确保该属性(property)是您所期望的。
同样对于禁用条件是!isPickUpPoint ,所以它会在它为假时触发。
对于必需的条件是isPickUpPoint所以它会在它为真时触发。
这也有点脱节,因为它看起来是相同的输入。

关于javascript - 需要 React Hook Form 动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63089761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com