溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

TypeScript中的react-router如何使用

發(fā)布時(shí)間:2024-07-09 15:44:06 來源:億速云 閱讀:83 作者:小樊 欄目:編程語言
  1. 首先,安裝react-router-dom包:
npm install react-router-dom
  1. 在應(yīng)用程序的根組件(通常是App.js)中,導(dǎo)入所需的react-router-dom組件:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
  1. 在根組件中使用Router組件包裹整個(gè)應(yīng)用程序,并在其中添加Route組件來定義路由和相應(yīng)的組件:
function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </Router>
  );
}
  1. 在需要導(dǎo)航的組件中,可以使用Link組件來創(chuàng)建導(dǎo)航鏈接:
import { Link } from 'react-router-dom';

function Navigation() {
  return (
    <nav>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
      </ul>
    </nav>
  );
}
  1. 在需要訪問路由參數(shù)的組件中,可以使用useParams鉤子來獲取路由參數(shù):
import { useParams } from 'react-router-dom';

function User() {
  let { id } = useParams();

  return <h2>User ID: {id}</h2>;
}

這樣,就可以使用react-router來實(shí)現(xiàn)在TypeScript中的路由導(dǎo)航和參數(shù)獲取了。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI