You need to enable JavaScript to run this app. NextJs:点击Form.Check对象时仅添加选中项值的实现问题
优惠活动
大模型
产品
解决方案
定价
更多

NextJs:点击Form.Check对象时仅添加选中项值的实现问题

问题修复方案

根因说明

  • 你之前的判断逻辑错误:checked选中状态挂载在e.target对象上,而非你定义的value变量上,value仅存储你绑定的record.verifyName字符串值,没有checked属性,导致判断始终不生效,每次点击都会执行push逻辑
  • 你编写的判断代码存在拼写错误:collection.push(valued)中的valued为无效变量
  • 缺少取消勾选时的数值移除逻辑,仅做新增会导致集合内数据无法和勾选状态同步

修复后的代码

基础修复(直接修改原有逻辑)

<Row>
    <p><b>Account Verification</b></p>
    {
        verifications.map(record => {
            return(
                <Col xs={12} md={3} mb={3}>
                    <Form.Group
                        key={record.id} 
                        className="mb-3" 
                        controlId={record.verifyName}
                        >
                        <Form.Check 
                            id={record.verifyName}
                            onChange={e=> {
                                const isChecked = e.target.checked;
                                const value = e.target.value;
                                if(isChecked) {
                                    collection.push(value);
                                } else {
                                    // 取消勾选时移除对应值
                                    collection = collection.filter(item => item !== value)
                                }
                                console.log(collection)
                            }}
                            key={record._id} tag="verify" value={record.verifyName} label={record.verifyName} />
                      </Form.Group>
                </Col>  
                )
        })
    }
</Row>

React State场景适配

如果你使用React的useState管理collection变量,不能直接修改原数组,需要用状态更新方法触发重渲染,参考写法:

// 声明状态
const [collection, setCollection] = useState([]);

// 对应onChange逻辑
onChange={e=> {
    const isChecked = e.target.checked;
    const currentValue = e.target.value;
    if(isChecked) {
        setCollection(prev => [...prev, currentValue]);
    } else {
        setCollection(prev => prev.filter(item => item !== currentValue));
    }
}}

内容的提问来源于stack exchange,提问作者Mark Willow Aldave

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 07:03:02