You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React默认选中选项的多选组件功能实现及状态咨询

React动态多选下拉框问题求助

现有代码已实现以下功能:

  • 下拉框展示州列表,支持多选州
  • 选中州后,展示对应下属城市列表且默认全部选中

需要实现的功能:

  • 取消部分已选中城市的选中状态
  • 将取消选中的城市存入变量

目前实现州下拉框、填充城市并默认选中的功能较为简单,但取消部分城市选中状态的实现存在困难,特此求助。

额外咨询

多选组件中的元素如何知晓自身处于选中状态?理解点击元素后将值传入数组的逻辑,但不清楚该选中状态变量的持久化位置及访问方式。

注:此处的「下一个下拉框」指选中州后重新渲染出的州下属城市列表。若采用第二个下拉框实现需求更可行也可,但仍未取得进展。

提供的代码

const { useState } = React;

function Example({ stateData }) {  
  
  const [data, setData] = useState(stateData);
  
  // Currently supports selecting state and cities, but
  // could be rewritten to utilise any number of levels of children
  function handleClick(e) {

    // On click grab the name of the object from
    // the element's dataset
    const { dataset: { name } } = e.target;
    
    // map over the data in state and if the obj name
    // matches the name in the dataset change "selected, and
    // do the same with its children, otherwise turn off "selected"
    setData(prev => {
      return prev.map(obj => {
        if (obj.name === name) {
          return {
            ...obj,
            selected: true,
            children: obj.children.map(child => {
              return { ...child, selected: !child.selected };    
            })
          };
        }
        return { ...obj, selected: false };
      });
    });
  }
    
  return (
    <main>
      <MultiSelect
        data={data}
        handleClick={handleClick}
      />
    </main>
  );

}

// If an object has children call the MultiSelect component
// with _that_ data
function MultiSelect({ data, handleClick }) {
  return (
    <ul>
      {data.map(obj => {
      
        // If the data object is selected and
        // it has a children prop which is an array
        // with at least one element in it...
        const showChildren =
          obj.selected &&
          obj.children &&
          obj.children.length > 0;
      
        return (
          <li
            key={obj.id}
            className={obj.selected ? 'selected' : ''}
            data-name={obj.name}
            onClick={handleClick}
          >{obj.name}
          {showChildren && <MultiSelect data={obj.children} />}
          </li>
        );

      })}
    </ul>
  );
}

const stateData = [
  {
    id: '1',
    name: 'Utah',
    selected: false,
    children: [
      { id: '1.1', name: 'Salt Lake' }
    ]
  },
  {
    id: '2',
    name: 'Oregon',
    selected: false,
    children: [
      { id: '2.1', name: 'Medford', selected: false },
      { id: '2.2', name: 'Portland', selected: false }
    ]
  }
];

const node = document.getElementById('root');
const root = ReactDOM.createRoot(node);
root.render(<Example stateData={stateData}/>);

内容的提问来源于stack exchange,提问作者user3782816

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 11:43:27