改变一个复选框的状态从一个useEffect钩子在React?



context的值。数字是1。我想根据context.number将输入检查值设置为true。所以如果语境。序号为1,则选中模块1的复选框,表示模块1已完成。我只能改变onChange事件的输入值,所以我假设我需要一个useEffect钩子,所以它会在上下文时自动执行。数量变化?

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>
</>
);
}

我把这是我的上下文文件,并能够让它工作。我意识到这是一个措辞拙劣的问题,但我还是找到了答案。useEffect不是问题所在,问题在于每个复选框只保存本地状态,所以如果我渲染另一个页面,复选框就会回到未选中状态。

import React, { createContext, useState } from "react";
const AppContext = createContext();
function AppProvider(props) {
//Determine the modules
const modules = [
{
title: `Introduction`,
subtitle: "Lesson 1",
},
{
title: `Overview`,
subtitle: "Lesson 2",
}
];
//set module number state
const [number, setNumber] = useState();
//Create a checked state for each module
const [checkedState, setCheckedState] = useState(new Array(modules.length).fill(false));
//change module number method
function completionHandler(value) {
setNumber(value);
}
//Change checked value method
function handleChange(position) {
const updatedCheckedState = checkedState.map((item, index) => (index == position ? !item : item));
setCheckedState(updatedCheckedState);
}
//export method and state value
const value = {
number: number,
modules: modules,
checkedState: checkedState,
handleChange: handleChange,
completionHandler: completionHandler,
};
return <AppContext.Provider value={value}>{props.children}</AppContext.Provider>;
}
export { AppContext, AppProvider };

相关内容

  • 没有找到相关文章

最新更新