javascript - 无法使用 ant design 和 React 更改多选的值

标签 javascript reactjs select multi-select antd

我有一个用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

当我运行它时:

  • select的选项是id而不是数据的值。

  • 当我点击全选时,所有值都会被选中,我清除它,它会被清除,但是当我重新全选时,它会被多次选中,我无法清除它。

我该如何修复它?

最佳答案

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

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

您的codesandbox中有一些涉及joursId的额外代码,我不确定。
Full CodeSandbox

关于javascript - 无法使用 ant design 和 React 更改多选的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56237825/

相关文章:

javascript - 谷歌地图 - 功能地理编码和标记

javascript - 选择当功能有自己的样式时不使用的交互样式

MySQL 在两个字母之间搜索

mysql - 使用其他表 MySql 中的特定选择更新新表

javascript - 使用ReactJS和Material-UI的Fake Select占位符

JavaScript 多项选择问卷。如何更改代码以便可以勾选多个答案? (与第8个一起)

javascript - 如何将 mongoDB 连接到 angular2 应用程序?

reactjs - TypeScript + React : How do I type a component that passes props to an html `img` element?

javascript - 如何在react material-ui中获取密码字段值

javascript - 为什么 React 需要 jsdom 进行测试?