【问题标题】: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?你怎么能告诉 reactJs 每个复选框都是唯一的,所以当我更改一个框的选中属性时,它不会勾选所有其他框?
【发布时间】:2020-03-26 13:22:28
【问题描述】:
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 组件呈现。

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

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

【问题讨论】:

    标签: javascript html reactjs forms


    【解决方案1】:

    您可以使用 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} />
    })
    

    【讨论】:

    • 没用。重建页面后仍然拒绝记住选中的复选框。
    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多