我正在和ReactJs
和React-Hook-Form
一起工作.我有一个组件,里面有一个汽车品牌的精选列表.当组件最初呈现时,我希望 Select 列表选项默认为值Other
,并有一个文本输入显示,以便用户可以输入 Select 列表中不存在的品牌.如果用户从 Select 列表中 Select 了一个现有的品牌,那么文本输入应该被隐藏.下面是我的代码:
export default function Test() {
type Car = {
brandId: number,
brand: string
}
const defaultBrandId = 5; // 'Other'
const [showBrandInput, setShowBrandInput] = useState<boolean>(true);
const { register, handleSubmit, setValue, getValues, watch} = useForm<Car>();
useEffect(() => {
fetchCarBrands();
}, [])
useEffect(() => {
setShowBrandInput(getValues().brandId === defaultBrandId);
}, [watch('brandId')]);
function fetchCarBrands() {
// API call to get select list data
// Set default select list value to 'Other'
setValue("brandId", defaultBrandId);
}
function onSubmit() {
alert("form submitted");
}
return (
<>
<Form onSubmit={handleSubmit(onSubmit)} noValidate>
<Div className="mb-4">
<FormLabel>Brand</FormLabel>
<Row>
<Col>
<Form.Select {...register("brandId")}>
<option value="1">Chevy</option>
<option value="2">Ford</option>
<option value="3">Honda</option>
<option value="4">Toyota</option>
<option value="5">Other</option>
</Form.Select>
</Col>
<Col>
{showBrandInput &&
<Form.Control type="text" {...register("brand")} />
}
</Col>
</Row>
</Div>
<Button type="submit" className="btn-dk-blue">
Submit
</Button>
</Form>
</>
)
}
上述代码最初正确地呈现了默认的 Select 列表值Other
,并且文本输入是可见的.如果我随后从 Select 列表中 Select 了不同的值,则文本输入将被隐藏.我的问题是,如果我随后从 Select 列表中重新 Select Other
,文本输入不会显示.