首页 > 解决方案 > 无法使用蚂蚁设计更改多选的值并做出反应

问题描述

我有一个用ant Design开发的多选,他的值是从后端获取的:

 "jours": [
        {
            "id": 1,
            "jour": "Lundi"
        },
        {
            "id": 2,
            "jour": "Mardi"
        },
        {
            "id": 3,
            "jour": "Mercredi"
        },
        {
            "id": 4,
            "jour": "Jeudi"
        },
        {
            "id": 5,
            "jour": "Vendredi"
        },
        {
            "id": 6,
            "jour": "Samedi"
        }
    ]

我的代码是:

    jour:[], jours:[], joursId:[], 
handleJourChange = (jour) => { 
    this.state.jours.map((jourId)=>{
      this.state.joursId.push(""+jourId.id+"");
      this.setState({
        joursId: this.state.joursId
      })
      console.log(this.state.joursId)
      if (jour.includes('all')) {
        this.setState({ jour: this.state.joursId });
      } 
      else {
        this.setState({jour :jour});
      }
    })
  }

<Select id="motif" name= "motif" mode="multiple" showArrow allowClear showSearch style={{ width: '535px' }} placeholder="Sélectionnez le(s) motif(s)" value={this.state.jour} onChange={this.handleJourChange} 
                                optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                          <Option value="all">Sélectionner tout</Option>
                          { this.state.id_user > 0 && this.state.jours.map((jour)=>
                            <Option key={jour.id} value={jour.id}>{jour.jour}</Option>
                          )}
                        </Select>

我的代码沙盒: https ://codesandbox.io/s/async-meadow-2clz5

当我运行它时:

我该如何解决?

标签: javascriptreactjsselectmulti-selectantd

解决方案


这可以通过将handleChange功能更改为:

handleJourChange = jour => {
  if (jour.includes("all")) {
    this.setState(prevState => ({
      jour: prevState.jours.map(item => item.id)
    }));
  } else {
    this.setState({
      jour
    });
  }
};

joursId我不确定您的代码盒中涉及一些额外的代码。
完整代码沙盒


推荐阅读