ReactJS中动态复选框受控实现:基于数组子集设置选中状态
解决方案:基于数组子集设置复选框选中状态
核心思路
把子集Array2转换为Set结构(提升元素查找效率),遍历Array1创建复选框时,判断当前元素是否存在于Set中,存在则设置checked属性为true。
原生JavaScript实现
const Array1 = ['apple', 'banana', 'orange', 'grape']; const Array2 = ['banana', 'grape']; // 转换为Set优化查找性能 const selectedItems = new Set(Array2); const container = document.getElementById('checkbox-container'); Array1.forEach(item => { // 创建复选框元素 const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.id = `chk-${item}`; checkbox.value = item; // 设置选中状态 checkbox.checked = selectedItems.has(item); // 创建标签 const label = document.createElement('label'); label.htmlFor = `chk-${item}`; label.textContent = item; // 组装并插入容器 const wrap = document.createElement('div'); wrap.appendChild(checkbox); wrap.appendChild(label); container.appendChild(wrap); });
React 函数组件实现
import React from 'react'; export default function CheckboxGroup() { const Array1 = ['apple', 'banana', 'orange', 'grape']; const Array2 = ['banana', 'grape']; const selectedSet = new Set(Array2); return ( <div className="checkbox-group"> {Array1.map(item => ( <div key={item} className="checkbox-item"> <input type="checkbox" id={`chk-${item}`} value={item} checked={selectedSet.has(item)} /> <label htmlFor={`chk-${item}`}>{item}</label> </div> ))} </div> ); }
Vue3 实现
<template> <div class="checkbox-group"> <div class="checkbox-item" v-for="item in Array1" :key="item"> <input type="checkbox" :id="`chk-${item}`" :value="item" :checked="selectedSet.has(item)" /> <label :for="`chk-${item}`">{{ item }}</label> </div> </div> </template> <script setup> const Array1 = ['apple', 'banana', 'orange', 'grape']; const Array2 = ['banana', 'grape']; const selectedSet = new Set(Array2); </script>
注意:元素为对象的情况
如果数组元素是对象(而非基础类型),需通过对象的唯一标识(如id)来判断归属:
const Array1 = [ { id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'orange' } ]; const Array2 = [{ id: 2, name: 'banana' }]; // 提取子集的id集合 const selectedIds = new Set(Array2.map(item => item.id)); // 遍历创建复选框时判断id Array1.forEach(item => { const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.checked = selectedIds.has(item.id); // 其他元素创建逻辑... });
内容的提问来源于stack exchange,提问作者jhansi mahato
相关产品推荐
相关产品推荐

