繁体   English   中英

你怎么能告诉 reactJs 每个复选框都是唯一的,所以当我更改一个框的 checked 属性时,它不会勾选所有其他框?

[英]How can you tell reactJs that each checkbox is unique so when I change the checked attribute for one box it doesn't tick all the other boxes?

import React, {useState} from 'react';




const Checkbox = props => (
    <input type="checkbox" {...props} />
  )

const GenerateProgramClasses = (props) => {

const [checkBoxes, setCheckBoxes] = useState({default:false})
const listOfClasses =
        Object.keys(props.classesDB).map(
            class =>
            <li key={props.areaOfStudy+'_'+ class}>
                <Checkbox
                    checked = //{ some function that picks true or false, and I got a lot of errors/warnings }
                    onChange = //{
                        (e)=> // Calls some handler function that would take e.target.checked 
                              // and store it with a key into a useState({default:false}) object, 
                              // the default is there because when the page gets rendered for the
                              // first time all checkboxes should be unchecked.
                    }    
                    onClick={(e)=> props.sumCredits(e, props.classesDB[class])}
                />
                {props.areaOfStudy + ": " + class + " "}
                Credits: {props.classesDB[class]}

            </li>
                )

return(
    <div>
        <p>Step: {props.pageNum}</p>
        <h2>Program Core: {props.areaOfStudy}</h2>
        <h3>Total Credits: {props.credit}</h3>
            <form>
            <ol>
                {listOfClasses}
            </ol>
            </form>
        <button onClick={() => props.previousPage()}>previous</button>
        <button onClick={() => props.nextPage()}>next</button>
    </div>
)
}

export default GenerateProgramClasses

上面是我的代码,它会生成一个页面,其中包含学校课程及其相应学分的复选框列表。 当我勾选复选框时,sumCredits 将运行,然后从总信用变量中添加/减去信用。 最后,当我单击我的下一个/上一个按钮时,pageNum 的状态将会改变,因为我有一个来自 App.js 的 switch 语句,这将触发再次使用 GenerateProgramClasses 组件呈现正确的页面。

当我点击我的前进按钮时,一切都很好。 但是,因为我每次单击按钮时都会重新呈现页面,所以我之前所有这些复选框的历史记录都将消失。 我试图通过创建一个新状态来解决这个问题,该状态将跟踪单击了哪个复选框,然后使用该键值对重建复选框列表。 这根本不起作用,出于某种原因,反应会同时检查所有框的真或假。 当我没有将唯一键值添加到我的列表元素之前,这发生在我身上。 我不确定这是否真的是造成它的原因。

那么你如何告诉 reactJs 当一个复选框被选中时记住它的状态以便下次你重新渲染页面时使用那些以前的状态作为参数再次重建复选框列表? 我已经解决了这个问题,否则我的总信用计数器计算会搞砸。谢谢。

您可以使用 map 函数的索引参数生成唯一值,并将该索引用作复选框的 id 属性

myarray.map((currElement, index) => {

  console.log("The current iteration is: " + index);
  //you can also modify index as per your requirement 

  <input id={index} type="checkbox" {...props} />
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM