如何在react js web应用程序的页面导航中更改Material UI工具栏中的标题



我有react功能组件MainToolBar。在导航到其他页面(功能组件(时,我需要更改MainToolBar的标题。我怎么能那样做?使用Context API或Redux或任何其他简单的东西

以下是MainToolBar.Js 的代码

export default function MainToolBar() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<Typography align="center" variant="h6" className ={classes.title}>
ERP System
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
</div>
);
}

以下是Thirdparty.js 的代码

function ThirdParty() 
{
return (
<div>
<label>ThirdParty</label>            
</div>
)
}
export default ThirdParty
layout.js
import {
BrowserRouter as ReactRouter,
Switch as ReactSwitch,
Route as ReactRoute,
} from "react-router-dom";

import ThirdParty from "./ThirdParty.js";

export default function Layout() {
return (
<div>
<ReactRouter>
<MainToolBar />
<ReactSwitch>
<ReactRoute exact path="/" component={SignInUp}> 
</ReactRoute>         
<ReactRoute exact path="/thirdparty" component= 
{ThirdParty}></ReactRoute>
</ReactSwitch>
</ReactRouter>
</div>
);
}

Context APIredux都是很好的解决方案。通过这种方式,您可以编写一个简单的效果挂钩,它将更新工具栏标题上下文/调度redux操作,从而更改它。这个挂钩将在Route组件呈现的主要组件内部调用。

另一个解决方案是根据路径为可选工具栏标题创建一个映射对象,但可能不太一致。这样,您就可以使用react router domuseLocation钩子来识别路径,并更改标题。例如,

import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
const titles = {
"/": "ERP System",
"/thirdparty": "Third Party"
};
...
// Inside Toolbar component
const location = useLocation();
const [title, setTitle] = useState(titles["/"]);
useEffect(() => {
setTitle(titles[location.pathname]);
}, [location.pathname]);
...

如果路径依赖于ID值,则效果内部需要更复杂的逻辑。

最新更新