简体   繁体   中英

How to use react router js without webpack in reactjs?

I'm new to reactjs. I'm struggling to set route change. Is there any simple solutions for router change event without webpack?

var PageOne = React.createClass({
  render: function() {
      return (
        <h2>Page 1</h2>
      );
    }  
});
var PageTwo = React.createClass({
  render: function() {
      return (
        <h2>Page 2</h2>
      );
    }  
});
var PageThree = React.createClass({
  render: function() {
      return (
        <h2>Page 3</h2>
      );
    }  
});

You can use HashRouter from react-router-dom which is easier to use (in my view) and works even after reloading the page.
Here an example:

  • First, install React Router v4: npm install --save react-router-dom
  • Then in your index or parent component use this code:
import { HashRouter, Route, Switch } from 'react-router-dom'
const App = () => (
  <HashRouter>
    <Switch>
      <Route path='/page1' component={PageOne} />
      <Route path='/page2' component={PageTwo} />
      <Route path='/page3' component={PageThree} />
    </Switch>
  </HashRouter>
)


  • Here is an example for your nav component:
import { Link } from 'react-router-dom'
const Nav = () => (
  <div>
    <Link to='/page1'>Page1</Link>
    <Link to='/page2'>Page2</Link>
    <Link to='/page3'>Page3</Link>
  </div>
)

Simple mechanics of React-router is below:

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

// inside your parent component add routs
<Switch>
   <Route path="/page1" exact render={<PageOne>} />
   <Route path="/page2" exact render={<PageTwo>} />
   <Route path="/page3" exact render={<PageThree>} />
</Switch>

// connect your parent component with Router
<Router history={history}>
  <AppConnected />
</Router>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM