iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 29
0
自我挑戰組

react.js 的學習筆記 (沒在用硬要學系列 第 29

day 29 細說 React router

  • 分享至 

  • xImage
  •  

今天這章會細說router 的用法

使用Link 來定義超連結

可以自動幫你產生href的連結

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router , Switch ,Route,useParams,Link} from 'react-router-dom';


const Child = () => {
  // We can use the `useParams` hook here to access
  // the dynamic pieces of the URL.
  let { idk } = useParams();

  return (
    <div>
      <h3>ID: {idk}</h3>
    </div>
  );
}


const Routers = () => {
  return(
    <>
    <Router>
    <h2>Accounts</h2>
      <ul>
        <li>
          <Link to="/netflix">Netflix</Link>
        </li>
        <li>
          <Link to="/zillow-group">Zillow Group</Link>
        </li>
        <li>
          <Link to="/yahoo">Yahoo</Link>
        </li>
        <li>
          <Link to="/modus-create">Modus Create</Link>
        </li>
      </ul>
    <Switch>
      <Route path="/:idk" children={<Child />} />
    </Switch>  
    </Router>
    </>
  );
}
ReactDOM.render(<Routers />, document.getElementById('root'));

https://ithelp.ithome.com.tw/upload/images/20200929/20110292sUrYM43Tzy.png
https://ithelp.ithome.com.tw/upload/images/20200929/20110292EIcgmcJXH0.png

這範例使用到

import {BrowserRouter as Router , Switch ,Route,useParams,Link} from 'react-router-dom';

BrowserRouter as Router <---這2個用法是一樣的,不管是用BrowserRouter還是Router一樣都不會抱錯
useParams() <---這是router 的參數,可取to="..."裡面的值

點擊後幫link加上class

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router , Switch ,Route,Link,useRouteMatch} from 'react-router-dom';

const Routers = () => {
  return(
<>
    <Router>
      <div>
        <Optext optext={true} to="/" t_s="Home" />
        <Optext to="/about" t_s="About" />

        <hr />

        <Switch>
          <Route exact path="/" children={<Home />}/>
          <Route path="/about" children={<About />} />
        </Switch>
      </div>
    </Router>
</>
  );
}

const Optext = ({ t_s, to, optext }) => {
  let match = useRouteMatch({
    path: to,
    exact: optext
  });

  return (
    <div className={match ? "active" : ""}>
      {match && "go to --- >"}
      <Link to={to}>{t_s}</Link>
    </div>
  );
}

const Home = () => {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

const About = () => {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}
ReactDOM.render(<Routers />, document.getElementById('root'));

https://ithelp.ithome.com.tw/upload/images/20200929/20110292UZK8YoTc53.png


上一篇
day 28 React 路由 安裝設定(router
下一篇
day 30 最後 打包 放到空間上
系列文
react.js 的學習筆記 (沒在用硬要學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言