我需要在我的应用程序中处理 2 个不同的 header :
首先,我正在考虑使用本地存储来保存我想要显示的菜单(
localStorage.setItem('menu', 'default’);
)所以当我在一个不需要菜单而只是简单栏的组件中时,我只是像这样重置 localStorage : localStorage.setItem('menu', ‘bar’);
但是这个想法(我知道这不是最好的)并没有重新渲染我的标题。
我该怎么办?
在我的渲染中,我有这样的东西:
render() {
let menu = localStorage.getItem('menu');
return (
<header>
{menu === 'bar' ? <TopBar/> : <MenuBar/>}
</header>
)
}
最佳答案
您的 Header 不会重新渲染,因为它的 Prop /状态没有改变。您只更改了 localStorage
这不会重新渲染您的组件。
我可以向您建议两种方法:
1. 根据您所在的路线,只需使用正确的标题:
// Home.js
const Home = props => <>
<MenuBar />
// The rest components of your page
</>
// Inside.js
const Inside = props => <>
<TopBar />
// The rest components of your page
</>
2.如果您有
<PageLayout />
组件,您可以使用 prop 有条件地渲染 Header:<PageLayout />
就是这样一个组件,在这里我们可以复用页面布局组件的组合。每个页面都有页眉、正文、页脚。与其在所有页面中复制相同的组件结构,不如将<PageLayout />
中的布局结构抽象出来。 .const PageLayout = ({ header === 'default', children }) => <>
<header>
{ header === 'bar' ? <TopBar /> : <MenuBar /> }
</header>
<body>
{children}
</body>
<Footer />
</>
// Home.js - Here will use the `default` Header
const Home = props => <PageLayout>
// The rest components of your page
</PageLayout
// Inside.js - Here we will use <TopBar />
const Inside = props => <PageLayout header='bar'>
// The rest components of your page
</PageLayout
关于javascript - 如何在 reactJS 中处理 2 Header?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56582042/