javascript 需要更改React中另一个组件内的状态变量

h7appiyu  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(142)

我需要更改UserProfile和ChangePassword组件中的值mainPageView,如何实现?进一步,我想在单击UserProfile中的按钮时将mainPageView值更改为false,在单击ChangePassword中的按钮时将其更改为true。以下是我的代码

import * as React from "react";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemText from "@mui/material/ListItemText";
import ListItemAvatar from "@mui/material/ListItemAvatar";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import Typography from "@mui/material/Typography";
import HomeIcon from "@mui/icons-material/Home";
import CakeIcon from "@mui/icons-material/Cake";
import Axios from "axios";
import { useState, useEffect, useContext } from "react";
import { LoginContext, UserContext } from "../../../Helper/UserContext";
import { Button } from "@mui/material";
import UserProfile from "./Profile";
import ChangePassword from "./Profile";

export default function MainProfile() {
  const { cookies } = useContext(LoginContext);
  const employee_id = cookies.emp_id;

  const [mainPageView, setMainPageView] = useState(true);

  return (
    <div>
      {mainPageView && <UserProfile />}
      {!mainPageView && <ChangePassword />}
    </div>
  );
}

描述USerProfile和ChangePassword组件的解决方案(代码段)

t40tm48m

t40tm48m1#

将父方法作为props传递,例如

{mainPageView && <UserProfile  updatevalue ={setMainPageView}/>}
 {!mainPageView && <ChangePassword updatevalue ={setMainPageView} />}
 
 
 
 
 const ChangePassword = (props) => {
  return (
    <div>
    <h1 onClick= { () =>
        props.updatevalue(false>)
      }
      > Something</h1>
    </div>
  )

}
export default ChangePassword;

相关问题