【问题标题】:React Router: Changing components and routes by buttonReact Router:通过按钮更改组件和路由
【发布时间】:2020-02-23 15:53:12
【问题描述】:

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

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

【问题讨论】:

  • 您正在安装react-router-dom,但您不使用它。这是您可以关注的示例reacttraining.com/react-router/web/example/basic
  • 所以你建议我在 routes.js 文件中添加 /component1 和 /component2,这样我就可以去那里了。

标签: reactjs react-router-dom


【解决方案1】:

是的,您可以使用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>

【讨论】:

  • 谢谢,我想我想太多了,忘记了琐碎的事情。
猜你喜欢
  • 2017-08-20
  • 2017-12-24
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
  • 2018-08-06
  • 2016-10-14
相关资源
最近更新 更多