繁体   English   中英

从 App.js 导航到 Places.js

[英]Navigating from App.js to Places.js

我是 React 的新手。我玩了很多。现在我想从 App.js 导航到 Places.js。我同意可以使用 React-router 来完成,但我还没有弄清楚成功地。 我需要这方面的帮助。说到这里,我尝试了几种使用 HashRouter、Route 和 Navlink 的组合,但所有的努力都是徒劳的。

这是我的 App.js

    import {Link,Router} from 'react-router-dom';
    import Places from './Places';
    import React, { Component } from "react";
    import { Card} from 'semantic-ui-react';


    class App extends Component {

    render() {

    return (
    <Router>
      <div className ="ui four stackable two column grid">

     <div className="column">
       <Card
         as = {Link} to = '/Places'
         header='Places'
         description='Click here to get list of places.'
        />
     </div>

...

     </div>
    </Router>

      );
    }
   }

这是我的 Places.js

 import { Card} from 'semantic-ui-react';
 import axios from 'axios';

  export default class Places extends React.Component {

...

基本上我有 App.js 和 4 个 UI 卡。当我点击每一张卡时,它应该加载相应 js 文件的内容。这是否符合 SPA 的要求?

定义您的路线。 您必须先导入react-router

在您的文件 app.js 中,您必须剪切另一个文件(例如 grid.js)中的内容。 'App' 将是你的应用程序的主要容器然后你将创建一个文件 routes.js 并描述你的路由:

import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './components/app';
import Grid from './components/Grid';
import Places from './components/Places';

export default (
  <Route path="/" component={App}>
    <IndexRoute component={Grid} />
    <Route path="places" component={Places} />
  </Route>
);

在这里,使用IndexRoute ,你说你的默认路由将加载“网格”,所以卡片列表。

然后,在 app.js 文件中,在渲染函数{this.props.children}中写入要显示元素“网格”和“位置”的位置。

最后,在您的文件“index.js”中,您将导入您的路由和路由器:

import { Router, browserHistory } from 'react-router';
import routes from './routes';

并且,在函数ReactDOM.render ,定义你的路由:

ReactDOM.render(
  <Router history={browserHistory} routes={routes} />
, document.querySelector('.container'));

您可以通过将路由保存在单独的文件中并从那里处理组件渲染来处理路由。

import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import {render} from 'react-dom';
import Places from '../Places.js';

render(
  <Router history={browserHistory}>
    <Route path='/' component={App}>
     <Route path='/Places' component={Places}></Route>
    </Route>
  </Router>, document.getElementById('app')
);

当您导航到“/Places”路线时,它将呈现 Places 组件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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