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

React项目中实现多选框最多选择3项的解决方案咨询

React 多选框最多选3项实现方案

核心思路

React 是数据驱动视图的框架,不需要像jQuery那样直接操作DOM,只需要通过useState维护选中项的状态,在状态更新时做数量限制即可。

完整修改后的组件代码

import * as React from 'react';
import { useTheme } from '@mui/material/styles';
import TextField from '@mui/material/TextField';

// 最大可选技能数量
const MAX_SELECTED_SKILLS = 3;
// 技能选项配置,统一管理避免重复代码
const SKILL_OPTIONS = [
  { id: 1, name: 'Business Development' },
  { id: 2, name: 'Marketing' },
  { id: 3, name: 'Coding' },
  { id: 4, name: 'UI/UX' },
  { id: 5, name: 'Product Management' },
  { id: 6, name: 'Leadership' },
  { id: 7, name: 'Operations' },
];

function CoFounder() {
  // 存储选中的技能ID数组
  const [selectedSkills, setSelectedSkills] = React.useState([]);

  // 多选框选中状态切换处理
  const handleSkillToggle = (skillId) => {
    const isAlreadySelected = selectedSkills.includes(skillId);
    if (isAlreadySelected) {
      // 已选中的选项执行取消选中逻辑
      setSelectedSkills(selectedSkills.filter(id => id !== skillId));
      return;
    }
    // 未选中的选项先判断是否已达上限
    if (selectedSkills.length >= MAX_SELECTED_SKILLS) {
      return;
    }
    // 未达上限则加入选中数组
    setSelectedSkills([...selectedSkills, skillId]);
  };

  return (
    <>
      <div className="mkw_figure">
        <h1 className="mkw_headline">
          Co Founders Match 
        </h1> 

        <h5 className="mkw_subheadline">
          Get the best matching Co Founder profile to connect and try your startup
        </h5>

        <h3 className="mkw_subheadline" style={{fontSize: 'x-large', margin: '0px', float: 'left', marginLeft: '80px', display: 'inline'}}>
          Co Founder skills you require
        </h3>

        <TextField placeholder="First skill would be priority skill. Type Own or Select from below"></TextField> 

        <div id="pill_multiselect" className="pill_multiselect">
          {/* 遍历技能配置渲染选项,避免重复代码 */}
          {SKILL_OPTIONS.map(skill => (
            <label key={skill.id} className="PillList-item">
              <input 
                type="checkbox" 
                name="feature" 
                checked={selectedSkills.includes(skill.id)}
                onChange={() => handleSkillToggle(skill.id)}
                value={skill.id} 
              />
              <span className="PillList-label">
                {skill.name}
                <span className="Icon Icon--checkLight Icon--smallest"><i className="fa fa-check"></i></span>
              </span>
            </label>
          ))}
        </div>
        <div> 
          <span id="not-valid" style={{color:'red'}}>
            {selectedSkills.length >= MAX_SELECTED_SKILLS ? '最多只能选择3项技能' : ''}
          </span>
        </div>

        <button className="mkw_test_apply_btn">Search</button>
      </div>    
    </>
  );
}

export default CoFounder;

关键修改说明

  • 修复了原代码中class属性写错的问题,React中必须用className替代HTML的class
  • 移除了原代码中字符串形式的onClick事件绑定,改用React标准的事件处理函数
  • 通过状态管理选中项,不需要操作DOM即可自动限制选中数量,选中超过3个时点击新选项不会生效
  • 新增选满时的红色提示文字,用户体验更好
  • 技能选项统一用数组管理,后续要修改选项只需要改数组即可,不需要修改渲染逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:15:02