首页 > 解决方案 > 如何构建动态包含标题的语义用户界面下拉列表?

问题描述

我有下拉选项

const options = [
    { key: '1', text: 'Example 1', value: 'Example 1', type:'ABC' },
    { key: '2', text: 'Example 2', value: 'Example 2', type:'XYZ' },
    { key: '3', text: 'Example 3', value: 'Example 3', type:'ABC' },
    { key: '4', text: 'Example 4', value: 'Example 4', type:'XYZ' },
  ];

我想动态构建语义-ui 下拉列表,以便每个下拉列表值都位于它们各自的“类型”值之下。

在这种情况下,示例 1、示例 3 将位于“ABC”标题标签下,示例 2、示例 4 将位于“XYZ”标题标签下。

ABC
  Example 2
  Example 4
XYZ
  Example 2
  Example 4

标签: javascriptreactjsdrop-down-menusemantic-uisemantic-ui-react

解决方案


我试图通过以下方式解决它。首先获取选项数组的所有不同类别。

categories = options.reduce((acc,curr)=> !acc.includes(curr.type)? [...acc,curr.type]: [...acc]  ,[]).slice()

然后我需要将所有可能的 json 映射到它的各自类型

categories.map(x=>{
  resOption[x]= options.filter(j => j.type===x).slice()
})

我的完整代码在这里

 var resOption = {}
  var categories =[]

categories = options.reduce((acc,curr)=> !acc.includes(curr.type)? [...acc,curr.type]: [...acc]  ,[]).slice()

categories.map(x=>{
  resOption[x]= options.filter(j => j.type===x).slice()
})

return(
  <Dropdown  selection >
    <Dropdown.Menu>
      {
        Object.keys(resOption).map((type)=>(
          <React.Fragment>
          <Dropdown.Header content={type} style={{color:"#5aa7e6"}} />
            {
              resOption[type].map((option)=>(
                <Dropdown.Item text={option.text} value={option.value}  onClick={onChange} />
              ))
            }
          <Dropdown.Divider />
          </React.Fragment>
        ))
      }
    </Dropdown.Menu>
  </Dropdown>
)

推荐阅读