iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 10
0
Modern Web

30天React從入門到入坑系列 第 10

DAY10:react-router v4

今天裝完react-router,寫完測試代碼要啟動server測試,竟然出現xxx undefined!!上網一查才發現,現行的v4和之前的v3寫法不一樣,而且Router已變成BrowserRouter,這個坑實在是很機車只好再去官網慢慢爬文件。我還沒有把文件給爬完,先分享一些基礎應用。

  1. url切換component
  2. 父元件傳遞參數和物件給子元件

react-router-web
https://reacttraining.com/react-router/web/guides/philosophy
安裝reactrouter
npm install react-router-dom

Link to對應Route path互相映射,每當點擊Link對應Route path切換到不同的component。

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import SayHi from './SayHi';
import App from './App';
import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'
import registerServiceWorker from './registerServiceWorker';

const Repos = () => (
  <div>
    <h2>Repos</h2>
  </div>
)

const About = () => (
  <div>
    <h2>About</h2>
  </div>
)

ReactDOM.render(
  <Router>
    <div>
      <ul>
        <li><Link to="/">App</Link></li>
        <li><Link to="/repos">Repos</Link></li>
        <li><Link to="/about">About</Link></li>
        <li>
          <Link to={{
            pathname: '/sayhi',
            state: { id: '1', message: 'hello, component' }
          }}>SayHi</Link>
        </li>
      </ul>
      <hr/>
      <Route exact path="/" component={App}/>
      <Route path="/repos" component={Repos}/>
      <Route path="/about" component={About}/>
      <Route path="/sayhi" render={props =><SayHi name="joe" {...props} />} />
    </div>
  </Router>,
  document.getElementById('root'));
registerServiceWorker();
  1. this.props.name是由SayHi name="joe"傳遞進來
  2. this.props.location.state.message是由Link state object傳遞進來
src/SayHi.js

import React, { Component } from 'react';

class SayHi extends React.Component {
  constructor(props) {
    super(props);
    console.log('url:'+props.match.url);
    console.log(this.props.location.state.message);
    this.state = {date: new Date()};
  }

  render() {
    return <h1>{this.state.date.toLocaleTimeString()} Hi, {this.props.name}</h1>;
  }
}

export default SayHi;

顯示畫面App
https://ithelp.ithome.com.tw/upload/images/20171229/20107317wj2bayuYB9.png

顯示畫面SayHi,console.log秀出傳遞訊息
https://ithelp.ithome.com.tw/upload/images/20171229/20107317OXHXmaV3dw.png


上一篇
DAY9:Conditional Rendering
下一篇
DAY11:Form Controlled Component
系列文
30天React從入門到入坑30

尚未有邦友留言

立即登入留言