选择选项后语义UI下拉列表未设置值



我使用的是React语义ui。我正在Fieldset中呈现一个下拉列表。我已经编写了代码,这样,一旦选择了一个选项,选项就会更新,这样所选的选项就会从列表中删除但当我从下拉列表中选择一个选项时,所选的值不会显示,而是显示为空

这是我的代码:这是我的下拉代码:

<Dropdown
name={`rows.${index}.mainField`}
className={"dropdown fieldDropdown"}
widths={2}
placeholder="Field"
fluid
selection  
options={mainFieldOptions}
value={row.mainField}
onChange={(e, { value }) => {
setFieldValue(`rows.${index}.mainField`, value)
updateDropDownOptions(value)                               
}
}                                                            
/>

我的选择:

let mainField = [
{ key: "org", text: "org", value: "org" },
{ key: "role", text: "role", value: "role" },
{ key: "emailId", text: "emailId", value: "emailId" },
]

此外,我有:

const [mainFieldOptions, setMainFieldOptions] = useState(mainField)

而且,

const updateDropDownOptions = (value:any) => {
let updatedOptions: { key: string; text: string; value: string }[] = []
mainFieldOptions.forEach(option => {
if(option.key != value){
updatedOptions.push({ key:option.key , text:option.key, value:option.key  })
}
})
setMainFieldOptions(updatedOptions)
console.log("mainfield", mainField)
}

在onChange中,如果我不调用updateDropDownOptions((方法,则会设置下拉值。但当我调用该方法时,它给出的值为空。请帮忙。

您的代码中几乎不需要更改

  1. 当添加一行〔{}〕时,您正在推送整个initialValue,但您只需要推送{},因此在推送方法中将代码更改为initialValues[0]
  2. 不需要为选项维护额外的状态。您可以根据values.rows中可用的其他行中的选定选项筛选选项

用于过滤选项的Util

const getMainFieldOptions = (rows, index) => {
const selectedOptions = rows.filter((row, rowIndex) => rowIndex !== index);
const filteredOptions = mainField.filter(mainFieldOption => !selectedOptions.find(selectedOption => mainFieldOption.value === selectedOption.mainField));
return filteredOptions;
}

在呈现每行时调用此util

values.rows.length > 0 &&
values.rows.map((row, index) => {
const  mainFieldOptions = getMainFieldOptions(values.rows, index);

工作沙盒

最新更新