【问题标题】:Multiple select dropdown with unique selection - React JS具有唯一选择的多选下拉列表 - React JS
【发布时间】:2019-08-29 06:51:13
【问题描述】:
  1. 我有 4 个选择下拉菜单。
  2. 所选值不应出现在下拉列表的其余部分中

我的state 看起来像这样

this.state = {
    selectedDropdownArray: {},
    dropdownArray: ['select','1','2','3','4','5']
}

下面是我的选择下拉组件

<SelectDropdown
    options={this.state.dropdownArray}
    value={this.getValue()}
    onChange={this.handleChange.bind(this)}                                         

handleChange 函数上,我只是先将值推送到其余工作所需的对象,然后我正在修改 dropdownArray 。下拉列表的数组列表应根据选择进行过滤。

下面是我的handleChange 函数,它过滤了下拉值。

handleChange(name, value){
    switch(name){
        case '1' :
            this.state.selectedDropdownArray["0"] = value === "select" ? null : value
        break;
        case '2' :
            this.state.selectedDropdownArray["1"] = value === "select" ? null : value
        break;
        case '3'
        ...
        ...
    }

    let filter = Object.values(this.state.selectedDropdownArray);
    let difference = this.state.dropdownArray.filter(x => !filter.includes(x));

}

如果选择了值为1 的第一个下拉列表,则difference 现在具有过滤数组[2,3,4,5],我可以将setState 转换为dropdownArray

但第一个下拉列表没有1 显示在此选择中,因为该数组已被过滤。

解决此问题的有效方法是为每 4 个选择下拉菜单进行唯一选择。

【问题讨论】:

    标签: javascript reactjs select drop-down-menu


    【解决方案1】:

    第一个:定义选择为数组:

    this.state = {
      selectedDropdownArray: [],
      dropdownArray: ['select','1','2','3','4','5']
    }
    

    如果由于其他原因不需要 - 稍后在过滤中不需要使用Object.values()

    第二个:避免在渲染中绑定,最好在构造函数中绑定this.handleChange 或使用箭头语法 - 阅读有关处理事件、传递参数的反应文档...

    3rd:你可以对每个实例分别使用选项过滤,比如:

    <SelectDropdown
      options={this.state.dropdownArray.filter(x => !this.state.selectedDropdownArray.includes(x) || x===this.state.selectedDropdownArray[0])}
      value={this.state.selectedDropdownArray[0] || ''}
      onChange={this.handleChange}
    />
    

    当然对下一个&lt;SelectDropdown/&gt; 实例使用下一个索引;)

    【讨论】:

    • 我使用selected 作为对象只是为了避免.push 有多个整体。
    • 你的意思是array.push 是否存在相同的键
    • 无需使用push - 只需使用索引数组访问 - 在控制台中尝试:var arr=[]; arr[3]=true; console.log(arr); arr[3]='whatever'; console.log(arr);
    • 知道了。。我实现成功了。谢谢你的时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2016-11-01
    • 2017-01-27
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多