如何从下拉菜单中重置 select 中的项目

How to reset items in select from dropwdown itself

我想 clear/remove/reset select 来自下拉菜单本身的选项,而不是来自 外部按钮 allowClear

假设 select 选项中的垃圾桶图标将重置所有值:

但是,我完全不知道如何用我当前的以下代码重置该值:

import st from "./AddToCartDropdown.module.css";
import {useState} from 'react';

import { Select } from 'antd';
import { DeleteFilled } from '@ant-design/icons';

const { Option } = Select;

function loopStock(n, selectedIndex){

    var elements = [];
    for(let i = 1; i <= n; i++){
      const qty = new String(i);
      const resultQty = qty.concat(" in cart");
      elements.push(<Option value={i}> <span className={st.addToCartSelect}> {i === selectedIndex ? resultQty : i} </span></Option>);
    }
    return elements;
}

const AddToCart = () => {
  const [selectedIndex, setSelectedIndex] = useState(-1);
  const onChange = (newSelectedIndex) => {
    setSelectedIndex(newSelectedIndex);
  }
  
    return (
      <div >
        <Select defaultValue="Add to Cart" onChange={onChange} className={st.addToCartDefault} bordered={false}>
          <Option value="delete"> <DeleteFilled /> </Option>
          {loopStock(5, selectedIndex)}
        </Select>
    
      </div>
    );
  };
  
  export default AddToCart;

当我 select 垃圾桶图标时,它应该显示 Add to Cart 而不是垃圾桶图标:

问题是在我 select 编辑垃圾桶图标以重置所有选项并返回 Add to Cart 默认值 [=15] 后,我很困惑如何设置状态=].

我是 React/JavaScript 的新手,仍在学习中。在搜索了所有解决方案之后,我认为最好在这里创建我自己的问题。谢谢!

您可以通过传递 value prop 和状态来将 select 作为 controlled 组件。将初始状态设置为 null 而不是 -1 以便我们可以使用占位符。

const [selectedIndex, setSelectedIndex] = React.useState(null);

当 selected 值为 delete 时,我们将状态设置为 null

const onChange = (newSelectedIndex) => {
    if(newSelectedIndex === 'delete'){
      setSelectedIndex(null)
    }else {
      setSelectedIndex(newSelectedIndex)
    }
  }

现在在 select 中添加 valueplaceholder 属性。

<Select placeholder="Add to Cart" value={selectedIndex} onChange={onChange}  bordered={false}>
          <Option value="delete"> <DeleteFilled /> </Option>
          {loopStock(5, selectedIndex)}
</Select>