簡體   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