首页 > 解决方案 > React Router:通过按钮更改组件和路由

问题描述

在 React 应用程序中,有一个带有 2 个按钮的页面。每个按钮呈现不同的组件,但是,路由/URL 不会改变。我怎样才能改变路线,只改变灰色区域?如果用户直接访问 URL,我该如何更改状态?

在此处输入图像描述

https://codesandbox.io/embed/elastic-fog-7hqk9?fontsize=14&hidenavigation=1&theme=dark

标签: reactjsreact-router-dom

解决方案


是的,您可以使用Switch,如果它与 URL 匹配,它将呈现您的组件。这是一个例子:

<Container>
  <Header />    // this will render in all cases (Fixed here for example)
  <Switch>
    <Route exact path="/component1" component={Component1} />
    <Route exact path="/component2" component={Component2} />
  </Switch>
</Container>

推荐阅读