从App.js导航到Places.js

问题描述 投票:1回答:2

我是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 {

...

基本上我有4个UI卡的App.js。当我点击它们中的每一个时,它应该加载相应的js文件的内容。这是否有资格作为SPA?

javascript reactjs react-router react-router-dom
2个回答
1
投票

定义路线。你必须先导入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,你说你的默认路由将加载'Grid'所以卡片列表。

然后,在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'));

0
投票

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

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组件。

© www.soinside.com 2019 - 2024. All rights reserved.