React可以使用react-router
库来获取路由参数。下面是使用react-router
获取路由参数的步骤:
react-router-dom
库。可以使用以下命令进行安装:npm install react-router-dom
BrowserRouter
和Route
组件,并设置路由规则。例如: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
对象的match.params
属性来获取路由参数。例如,在Product
组件中获取id
参数:import React from 'react';
const Product = (props) => {
const { id } = props.match.params;
return <h1>Product ID: {id}</h1>;
}
export default Product;
在上面的例子中,当访问/product/123
时,Product
组件会被渲染,并且id
参数的值为123
。