React可以使用react-router
庫(kù)來(lái)獲取路由參數(shù)。下面是使用react-router
獲取路由參數(shù)的步驟:
react-router-dom
庫(kù)。可以使用以下命令進(jìn)行安裝:npm install react-router-dom
BrowserRouter
和Route
組件,并設(shè)置路由規(guī)則。例如:import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Home from './Home';
import Product from './Product';
const App = () => {
return (
<Router>
<Route exact path="/" component={Home} />
<Route path="/product/:id" component={Product} />
</Router>
);
}
export default App;
props
對(duì)象的match.params
屬性來(lái)獲取路由參數(shù)。例如,在Product
組件中獲取id
參數(shù):import React from 'react';
const Product = (props) => {
const { id } = props.match.params;
return <h1>Product ID: {id}</h1>;
}
export default Product;
在上面的例子中,當(dāng)訪問(wèn)/product/123
時(shí),Product
組件會(huì)被渲染,并且id
參數(shù)的值為123
。