在React中的页面之间切换

时间:2018-09-23 22:50:45

标签: javascript reactjs react-router

我是React的新手,并且有一个(可能是)愚蠢的问题。如何在React.js中的不同JavaScript页面之间切换?

我的一个页面上有一个按钮,我想链接到另一个javascript页面。我了解路由器,但这不符合我的需求。

Web App Structure

谢谢, 马克·布鲁克特(Mark Bruckert)

2 个答案:

答案 0 :(得分:3)

使用react-router定义页面并在页面之间切换

https://reacttraining.com/react-router/

答案 1 :(得分:2)

这是基于react-router文档中的示例。 React Router可能是最简单的客户端路由解决方案。编码愉快。

See the complete example on Stackblitz.

import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

const Nav = () => (
  <div>
    <ul>
      <li><Link to="/">Home</Link></li>
      <li><Link to="/about">About</Link></li>
    </ul>
  </div>
);

const HomePage = () => <h1>Home Page</h1>;
const AboutPage = () => <h1>About Page</h1>;

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
      <Router>

        {/* Router component can have only 1 child. We'll use a simple
          div element for this example. */}
        <div>
          <Nav />
          <Route exact path="/" component={HomePage} />
          <Route path="/about" component={AboutPage} />
        </div>
      </Router>
    );
  }
}

render(<App />, document.getElementById('root'));