【发布时间】:2021-11-16 09:37:49
【问题描述】:
您好,我想知道如何将“Indeterminate”应用于我的代码复选框示例:
我知道文档就在那里,但我无法让它发挥作用这是我的尝试,我想说我很接近但显然错过了一些非常重要的东西
这个想法是,当我单击“父级”时,所有这些都被单击,所有这些都更改为已选中,并且它们都将数据发送到一个变量,当我取消单击时,它们应该将其删除,当我删除时一个特别是它应该只删除那个特别的(那个已经在工作,但是如果我必须为父级添加其他东西,那就不行了)
他们每个人都做我想做的事,但我想添加父/主,所以我可以检查所有这些:
这是我的代码:
[根据我目前收到的帮助编辑代码]
//Functions
//set all students
const [allStudentsID, setAllStudentsID] = useState([]);
const setAllStudents = () => {
setAllStudentsID(Array.isArray(estudiantes) ? allStudentsID.length && estudiantes.length === allStudentsID.length ? [] : estudiantes.map(x=> x.id):[]);
console.log(allStudentsID)
}
console.log 如下所示:
//set individual one by one (works)
const [studentID, setStudentID] = useState([])
const setStudent = (estudiante) => {
if(!studentID.find(id => id === estudiante)){
setStudentID([ ... studentID, estudiante]);
}
else {
setStudentID(studentID.filter(studentId => studentId !== estudiante))
}
console.log(studentID)
}
Mapping/Render:
//Titles (not sure if I'm setting up correctly the checkbox)
<thead>
<tr className="Lista">
<Checkbox
color = "primary"
id = "checkBox"
onChange = {() => setAllStudents()}
checked={allStudentsID.length === estudiantes.length}
indeterminate={allStudentsID.length > 0 && allStudentsID.length < estudiantes.length}
/>
<th>Nombre</th>
<th>Colegio</th>
<th>Grado</th>
<th>Accion</th>
</tr>
</thead>
//Table (this works)
{estudiantes.map((estudiantes, index) => (
<tr key={estudiantes.id || index}>
<td>
<Checkbox
checked={!!studentID.find( id => id === estudiantes.uid)}
color = "primary"
id = "checkBox"
onChange = {() => setStudent(estudiantes.uid, index)}
inputProps={{ 'aria-label': 'controlled' }}
/>
</td>
... some code that will finish the table
【问题讨论】:
-
如果你使用的是 MUI,那么你应该看看
DataGrid组件
标签: reactjs checkbox material-ui