【问题标题】:Clear selected options of one react-select which depends on the other react-select清除一个依赖于另一个反应选择的反应选择的选定选项
【发布时间】:2022-11-14 19:36:51
【问题描述】:

我在两个反应选择中有两个数据集。 例如:

options2={
[value: 1, label:"apple",relationKey=1],
[value: 2, label:"orange",relationKey=2],
[value: 3, label:"banana",relationKey=2],
[value: 4, label:"pineapple",relationKey=2],
}

options1 ={
  [value: 1, label: "drink 1", relationKey=1],
  [value: 2, label: "drink 2", relationKey=2]
}

现在我有两个反应选择,其中第二个取决于从第一个中选择的值。

首先选择:

        <Select
        options={options1}
        placeholder="Choose..."
        isSearchable={true} 
        onChange={handleChange}
        isMulti
        />

二选一:

        <Select
        options={options2}
        placeholder="Choose..."
        onChange={handleChange}
        isMulti
        />

现在该方案运行良好,将选定的值相互转移,仅显示所需的选项和所有这些。因此,当我从第一个选择中选择Drink 1 时,它应该只给我带有relationKey=1 的选项,如果我选择drink 2,它也应该列出选项2 中的其他选项。 这工作得很好。

我想要做的是:当我选择Drink 1Drink 2 并从第二个选择中选择apple, orange, banana, pineapple 时,如果我取消选择Drink2,我应该只有apple 在第二个选择选项列表中,因为Drink1是唯一一个被选中的。

我已经尝试过大量的 if/else,但数据集是动态的,我不能总是知道它们的关系键和它们的值......

希望我足够清楚,提前谢谢你。

【问题讨论】:

    标签: reactjs react-select


    【解决方案1】:

    可以使用filterOption

       <Select
        options={options2}
        placeholder="Choose..."
        onChange={handleChange}
        filterOption={filterOptions}
        isMulti
        />
    
    
    const filterOptions = (
      option: { label: string; value: string; relationKey: any },
      input: string
    ) => {
      if (input) {
        return option.relationKey === firstSelectOptionValue.relationKey;
      }
      return true;
    };
    

    【讨论】:

    • 试试这个例子。
    【解决方案2】:
        var options1 = [
          { "value": 1, "label": "drink 1", relationKey:1 },
          { "value": 2, "label": "drink 2", relationKey:2 },
        ];
        
        var options2 = [
          { "value": 1, "label": "apple", relationKey:1 },
          { "value": 2, "label": "orange", relationKey:2 },
          { "value": 3, "label": "banana", relationKey:2 },
          { "value": 4, "label": "pineapple", relationKey:2 },  
        ];
    
    <ReactSelect options={options1} onChange={(e)=>{ 
                      // set your state here of parent
                    }}/>
                      
    
                      <ReactSelect options={options2.filter(function (el) {
                        return el.relationKey === 'your parent selected id will be here';
                      })}/>
    

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 2021-07-21
      • 2012-01-30
      • 2018-06-29
      • 2020-10-09
      • 2019-03-08
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      相关资源
      最近更新 更多