react路由跳转携带参数
时间: 2023-10-13 20:11:06 浏览: 119
在React路由中,可以使用React Router提供的withRouter高阶组件或者Hook来获取当前路由的参数。
使用withRouter:
```javascript
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
handleClick = () => {
const { history } = this.props;
history.push(`/path/${paramValue}`);
}
render() {
return (
<button onClick={this.handleClick}>跳转</button>
);
}
}
export default withRouter(MyComponent);
```
使用Hook:
```javascript
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleClick = () => {
history.push(`/path/${paramValue}`);
}
return (
<button onClick={handleClick}>跳转</button>
);
}
export default MyComponent;
```
在路由配置中,可以使用动态路由来获取参数:
```javascript
<Route path="/path/:paramValue" component={MyComponent} />
```
在MyComponent组件中,可以使用props.match.params.paramValue来获取参数值。例如:
```javascript
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
handleClick = () => {
const { history, match } = this.props;
history.push(`/path/${match.params.paramValue}`);
}
render() {
const { match } = this.props;
const paramValue = match.params.paramValue;
return (
<div>{paramValue}</div>
);
}
}
export default withRouter(MyComponent);
```
阅读全文