我有两个下拉列表,在右边选择一个选项应该更新左边的选项。
第一个是frequencyDays
,第二个是frequencyInterval
。
假设我有一个函数,它将返回给定ID的<option>
s数组(第二个param的值)
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窗体在初始化时正确填充,但不更新.
第一个下拉(frequencyDays)
<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做它的表单绑定,但除此之外,调用第一个下拉列表的重新填充,但得到错误。
发布于 2021-05-18 14:22:53
我离得很近。解决方案是保持状态变量。使用您的<option>
数组。然后onChange
,记住语法是onChange={e => { .. }}
(双大括号),包括默认的Formik handleChange
+自定义状态设置器。
// 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));
}
}
>
https://stackoverflow.com/questions/67576363
复制相似问题