简体   繁体   中英

React Hook Form reset Controller (value) to default

Here is an example of my component, wrapped into Controller

<div className="mt-1">
    <Controller
       control={control}
       name="selectedBirthMonth"
       defaultValue={selectedMonth}
       render={({ field }) => (
       < SelectBirthMonth 
         field={field}
         startYear={startYear}
         selectedYear={selectedYear}
         months={months}
         value={selectedMonth}
         reducedMonths={reducedMonths}
         onChange={useEffect(() => monthSelect(field.value)), [selectedMonth]}/>
   )}
 />
</div>

For now I am just trying to reset it with a button. Later I'd love to conditionally reset, depending on the value in a sibling component. Would be great to get it work with the button in the first place:

<input
  style={{ display: "block", marginTop: 20 }}
  type="button"
  onClick={() =>
   reset(selectedBirthMonth)
  }
  value="Reset with values"
/>

I get en error: selectedBirthMonth is not defined. Bassicaly, what I am aming for,on click, the whole component goes to default / a state it had when first rendered. What am I missing?

reset didn't do the job somehow, but setValue did. However I am setting to a value, not to the original state after first render, but in my case it's same.

<input
  style={{ display: "block", marginTop: 20 }}
  type="button"
  onClick={() =>
    etValue('selectedBirthMonth', lastAvaliableMonth)
  }
  value="Reset with values"
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM