I'm recently learning to work with Ionic and React and I wanted to make a forms with an IonSelect item where the user chooses a gender option. If the user chooses female
then I have a function where another IonInput appears otherwise it stays hidden. Like this:
<IonItem><IonLabel>Gender</IonLabel>
<Controller as = {
<IonSelect placeholder="Please select...">
<IonSelectOption value="female" >Female</IonSelectOption>
<IonSelectOption value="male">Male</IonSelectOption>
</IonSelect>
}
control={control}
name="gender"
onIonChange={onChange}/></IonItem>
{showOptions ?
<IonItem>
<IonLabel position="floating">Date:</IonLabel>
<IonDatetime placeholder="Select date"></IonDatetime>
</IonItem>: null}
And the functions:
const [showOptions, setShowOptions] = React.useState(false);
const onChange = ((e: React.ChangeEvent<HTMLIonSelectElement>) : void => {
const value = e.currentTarget.value;
console.log(value);
if (value == "female"){
setShowOptions(true);
}
else if (value == "male"){
setShowOptions(false);
}})
It's working fine, the hidden item appears when the user selects female
, but for some reason after the onChange
event occurs the IonSelectOption
is deselected, going back to the placeholder text. How do I fix this and keep the original selection after the onChange
event?
edit
So I used the watch function and now it's working, the only problem is that everytime I choose either the female or male option, my other component wrapped around Controller resets.
This is my code now:
<IonItem>
<IonLabel position="floating">Email:</IonLabel>
<Controller control= {control} as =
{<IonInput type="email"/>}
name= "email"
rules= {{required:true}} />
</IonItem>
<IonItem>
<IonLabel >Gender:</IonLabel>
<Controller render={({onChange}) => (
<IonSelect placeholder="Please select..." id="gender"
onIonChange={(e) => {
console.log(e);
onChange(e.detail.value)
}}>
<IonSelectOption value="female" >Female</IonSelectOption>
<IonSelectOption value="male">Male</IonSelectOption>
</IonSelect>
)}
control={control}
name="gender"
rules={{required: true}} />
</IonItem>
{watchGender == "female" ?
<IonItem>
<IonDatetime placeholder="Select date"></IonDatetime>
</IonItem>: null}
The functions:
const {control, watch, handleSubmit} = useForm();
const watchGender= watch("gender", "");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…