【发布时间】:2021-11-06 10:14:57
【问题描述】:
context.number 的值为 1。我想根据 context.number 将输入检查值设置为 true。因此,如果 context.number 为 1,则选中 Module 1 的复选框,表明 Module 1 已完成。我只能从 onChange 事件中更改输入值,所以我假设我需要一个 useEffect 挂钩,以便在 context.number 更改时自动执行它?
import React, { useState, useContext, useEffect } from "react";
import { Link } from "react-router-dom";
import { AppContext } from "../context/AppContext";
export default function Menu() {
const context = useContext(AppContext);
//Determine the modules
const modules = [
{
title: `Introduction`,
subtitle: "Lesson 1",
},
{
title: `Overview`,
subtitle: "Lesson 2",
}
];
//Create a checked state for each module
const [checkedState, setCheckedState] = useState(new Array(modules.length).fill(false));
//Change checked value method
const handleOnChange = (position) => {
//map through checked states array, if position === mapped item index, flip the value
const updatedCheckedState = checkedState.map((item, index) => (index === position ?
!item : item));
//set that items state to the new value in the array
setCheckedState(updatedCheckedState);
};
return (
<>
<div>
{modules.map((module, index) => (
<div className={styles.menuCard}>
<Link key={index} to={`/Module/${index + 1}`}>
<h2>{module.title}</h2>
<p>{module.subtitle}</p>
</Link>
<input
id={`check${index}`}
type="checkbox"
onChange={() => handleOnChange(index)}
checked={checkedState[index]}
/>
</div>
))}
</div>
</>
);
}
【问题讨论】:
-
真正的解决方案是将以下代码移动到上下文中并将状态保存在其中。
标签: reactjs checkbox react-router state use-effect