根据 Formik 表单中的另一个选择重新填充 Select 下拉列表

Re-populate a Select dropdown depending on another selection in a Formik form

我有两个下拉菜单,在其中选择右侧的选项会更新左侧的选项。

第一个是frequencyDays,第二个是frequencyInterval

假设我有一个函数,它将 return 给定 ID 的 <option> 数组(第二个参数的值)

const getOptionsDays = (value) => {
    let options = [];
    //... some logic in a loop ...
    for (var i = 0; i < N; i++) {
       options.push(<option key={i} value={i}>{i}</option>);
    }
    return options; // Returns an array of <option> elements
}

Formik 表单在初始化时正确预填充,但不会更新。

第一个下拉列表(频率天数)

<Form.Control as="select"
  id="dropdownFrequencyDays"
  name="frequencyDays"
  value={values.frequencyDays}
  onChange={handleChange}
>
    <option></option>
    { getOptionsForDays(values.frequencyInterval) }
</Form>

第二次下拉(frequencyInterval),onChange应该触发重新填充

<Form.Control as="select"  
              id="dropdownFrequencyInterval"
              name="frequencyInterval"
              value={values.frequencyInterval}
              onChange={e => /* Should do something here but getting syntax errors */
                         // Call built-in Formik handleChange 
                         handleChange(e);
                         // Additional: call to repopulate 1st dropdown?
                         // ...errors
                       }
>

我想让 Formik 进行表单绑定,但另外调用第一个下拉列表的重新填充,但出现错误。

我很接近。解决方案是保留状态变量。用你的 <option> 阵列。然后 onChange,记住语法是 onChange={e => { .. }}(双括号),包括默认的 Formik handleChange + 自定义状态 setter.

// State var to keep option array
const [frequencyDayValues, setFrequencyDayValues] = useState([]);

...

// On initialization, set your option array (with whatever logic needed, 
// e.g. populateOptions() for an initial code of 55)
useEffect(() => {    
    setFrequencyDayValues(populateOptions(55));
}, []);

// The option array must contain actual <option> elements, e.g.
const populateOptions = (value) => {
    let options = [];
    options.push(<option value={..}>Label</option>);
    return options;
}
...

{/* Dependent Dropdown: Displays whatever is currently in frequencyDayValues */}
<Form.Control as="select"
              name="frequencyDays"
              value={values.frequencyDays}
              onChange={handleChange}
>
    <option></option>
    {/* Populate Frequency Days from current state variable */}
    {frequencyDayValues}
</Form.Control>

{/* Triggering Dropdown: onChange does both the Formik handleChange AND custom update */}
<Form.Control as="select" 
              name="frequencyInterval"
              value={values.frequencyInterval}
              onChange={e => {
                  // Call default Formik handleChange()
                  handleChange(e);
                  // Additionally set the new frequencyDayValues state variable
                  // based on e.target.value
                  setFrequencyDayValues(populateOptions(e.target.value));
                }
              }                                                      
>