通过Link

时间:2019-09-09 11:56:50

标签: reactjs react-router react-router-dom

我是使用React Router的新手。我一直在尝试使用它,当我手动更改url路径时它可以工作。但是,当我使用Link标签导航到新路径时,它什么也没做。这是我的App.js

const newRoute = () => {
  return (
    <div id="colorlib-page">
      <div id="container-wrap">
        <Sidebar></Sidebar>
        <div id="colorlib-main">
          <Introduction></Introduction>
          <About></About>
          <Timeline></Timeline>
        </div>
      </div>
    </div>
  )
}
class App extends Component {
  render() {
    return (
      <BrowserRouter>
      <div>
      <Sidebar></Sidebar>
        <Switch>
          <Route path="/" component={newRoute} exact/>
          <Route path="/gallery" component={Gallery} />
          <Route component={Error}/>
        </Switch>
      </div>
      </BrowserRouter>
    );
  }
}

export default App;

当我手动转到http://localhost:3000/gallery时,它可以工作。但是Link是我猜问题出在哪里。 Sidebar组件是按钮的导航位置。这是Sidebar组件:

export default class Sidebar extends Component {
  render() {
    return (
      <div>
        <div>
          <nav href="#navbar" className="js-colorlib-nav-toggle colorlib-nav-toggle" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"><i /></nav>
          <aside id="colorlib-aside" className="border js-fullheight">
            <div className="text-center">
              <div className="author-img" style={{backgroundImage: 'url(images/about1.jpg)'}} />
              <h1 id="colorlib-logo"><a href="index.html">Shuvro Sarker</a></h1>
              <span className="email"><i className="icon-mail"></i> gmail</span>
            </div>
            <nav id="colorlib-main-menu" role="navigation" className="navbar">
              <div id="navbar" className="collapse">
                <ul>
                  <li className="active"><a href="#home" data-nav-section="home">Introduction</a></li>
                  <li><a href="#about" data-nav-section="about">About</a></li>


                  // Here's the Link which isn't working

                  <Link to="/gallery">Gallery</Link>

                  <li><a href="#timeline" data-nav-section="timeline">Timeline</a></li>
                </ul>
              </div>
            </nav>
              <p><small>
                Something coming soon !!
              </small></p>
            </div>
          </aside>
        </div>
      </div>
    )
  }
}

我还能通过该链接更改网址吗?

2 个答案:

答案 0 :(得分:0)

尝试将补充工具条包装在withRouter中的'react-router'中;

import { withRouter } from 'react-router';

class Sidebar extends Component {
    ...
}

export default withRouter(SideBar);



答案 1 :(得分:0)

我认为您需要添加WithRouter,而不仅仅是导出组件。

import { withRouter } from 'react-router-dom'

class Gallery extends Component{
}
export default WithRouter(Gallery)