我需要在我的应用程序中处理 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。根据您所在的路线,只需使用正确的 Header:
// 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/