【问题标题】:Routing from one component to another in React在 React 中从一个组件路由到另一个组件
【发布时间】:2020-07-01 20:24:19
【问题描述】:

我的应用由以下组件构成。

<App>
  <Header/>
  <Content/>
  <Footer/>
</App

这是我的应用组件,

function App() {
    return (
        <Router>
            <div className="App">
                <Header/>
                <Content/>
                <Footer/>
            </div>
        </Router>
    );
}

这是标题,

const Header = () => (
    <header className="homepage-header">
        <div className="container containerLogo">
            <img src={logo} alt="Logo"/>
        </div>
        <div className="container containerNav">
            <ul>
            <li><NavLink to="/"> Overview </NavLink></li>
            <li><NavLink to="/how-it-works">How it works</NavLink></li>
            <li><NavLink to="/plans-and-pricing">Plans & Pricing</NavLink></li>
        </ul>
        </div>
        <div className="container containerButton">
            <button className="signInButton">Sign In</button>
            <button className="signUpButton">Sign Up</button>
        </div>

    </header>
);

这是我的内容,

const Content = () => (
    <Switch>
        <Route path="/about"><Home/></Route>
        <Route path="/how-it-works"><Works/></Route>
        <Route path="/plans-and-pricing"><Plans/></Route>
    </Switch>

);

这不起作用 - 没有渲染任何组件。 如何从Header 路由到Content 内的不同组件?

我了解路由的工作原理并将使用客户端路由。指向不同页面的链接在这里是锚标记,因为我不确定要在 BrowserRouter 中包装什么组件。
我是 React 的新手,所以这个问题。

【问题讨论】:

  • reacttraining.com/react-router/web/guides/quick-start - 顶部的代码有几乎相同的用例示例,如果您不明白其中的任何部分,请告诉我
  • @tachko 我不确定你是否理解我的要求。我的路由器位于 Header 内,它在 Content 组件内路由不同的组件。您提供的示例没有展示类似的内容。组件在路由器所在的同一组件内呈现。
  • 你使用react-router-dom吗?
  • @MartialAnouman 是的,我正在使用react-router-dom
  • 看起来您没有任何在根级别呈现的组件,即exact path = "/"。能否在 Home 组件上临时设置上述路径。

标签: reactjs react-router-dom


【解决方案1】:

基本上,您需要将所有应用程序包装在BrowserRouter 中。看下面的结构:

路由组件

import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'

export const Routes = () => (
    <Router>
        {// Part of your app which never change}
        <Header/>
        {// Part of your app which change with routing}
        <Switch>
            <Route path='...' component={/* Component to reach with this route */} />
        </Switch>
        {// Part of your app which never change}
        <Footer/>
    </Router>
)

应用组件

// import Routes component
const App = () => (<Routes />)

路由部分在Switch 组件之间,所以这是设置导航的地方。即使HeaderFooter 组件没有更改,它们也可能会保留链接以触发导航。它们必须在 Router 组件内。

【讨论】:

  • 这不能回答我的问题。您的 Switch 在Header 之外。我的问题很具体,我将从Header 内部路由,并且组件需要在Content 内部呈现。
  • 你所说的«路由在标头内»是什么意思?
  • @root 我相信 Switch 组件只需要包装 Route 组件。您也可以避免一起使用 Switch。 BrowserRouting 是需要包装 Header 和 Content 的组件,看起来你已经完成了。
猜你喜欢
  • 1970-01-01
  • 2018-10-18
  • 2020-11-17
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2022-08-17
  • 2019-08-23
相关资源
最近更新 更多