gpt4 book ai didi

react-router - 显示某些组件时隐藏组件(使用 react 路由器)

转载 作者:行者123 更新时间:2023-12-02 20:47:04 25 4
gpt4 key购买 nike

我有下面的渲染功能。

class App extends Component {
render() {
return (
<Router>
<div>
<Header/>
<Switch>
<Route exact path="/" component={TestApp}/>
<Route exact path="/chat" component={ChahtView1}/>
<Route exact path="/chat/invite" component={ChatView2}/>
<Route exact path="/chat/chatting" component={ChatView3}/>
<Route component={NotFound}/>
</Switch>
</div>
</Router>
);
}
}

在这种情况下,每个页面都会显示 Header 组件。我想要做的是当 NotFound 组件出现时隐藏 Header

我该怎么做?请帮助我!
谢谢。

最佳答案

您可以使用react-router-dom中的“withRouter”提供的“location”对象来有条件地显示或隐藏组件,例如:

const Main = withRouter(({location}) => (
<div>
{location.pathname !== "/" && <Header/>}
<Switch location={location}>
<Route path="/" exact component={HomePage}/>
<Route path="/first-page" component={First}/>
<Route path="/second-page" component={Second}/>
<Footer />
</Switch>
<div>
)

有关“位置”的更多信息:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md

关于react-router - 显示某些组件时隐藏组件(使用 react 路由器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43916689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com