reactjs - 如何重定向到函数中的另一个组件?
问题描述
在我的 app.tsx 中,我有这个带有 react-router-dom 的结构:
<BrowserRouter>
<Switch>
<Route path={"/login"} component={Login}/>
<Route path={"/home"} component={HomeScreen}/>
<Route path={"/user"} component={UserMenu}/>
<Route path={"/profile"} component={ProfileScreen}/>
{<Redirect to={"/login"}/>}
</Switch>
</BrowserRouter>
在每个组件中,我想要一个允许我在它们之间移动的函数,例如,我尝试过 this.props.history.push () 但它对我不起作用,有什么想法吗?
解决方案
如果您正在使用功能组件,则可以使用 useHistory。
import React from 'react';
import { useHistory } from 'react-router-dom';
const Hello = () => {
const history = useHistory();
const handleClick = () => history.push('/route');
return (
<button type="button" onClick={handleClick}>
Navigate
</button>
);
};
如果您使用的是类组件,则可以使用 withRouter:
import { withRouter } from 'react-router-dom'
class Hello extends React.Component {
handleClick = (user) => {
this.props.history.push('/route')
}
render() {
return (
<button type="button" onClick={this.handleClick}>
Navigate
</button>
)
}
}
export default withRouter(Hello)
推荐阅读
- c++ - 如何使用 CMake 在 macOS 上链接 fftw3?
- python - 即使安装成功,Raspberry Pi 也找不到 Tesseract
- python - 我试图在 odoo 中安装一个新模块但发生错误,AttributeError: 'str' object has no attribute 'setdefault'
- google-cloud-platform - FlexRs=SPEED_OPTIMIZED 在 Dataflow 中的作用是什么?
- apache-spark - 在 Pyspark 中管理多个数据框
- docker - Docker更改命名卷的位置
- reactjs - 如何在 ant design 崩溃中更改图标(Accordian)
- javascript - 基于重复属性删除数组元素
- php - Symfony & Panther:Panther 不加载 - 无法创建 PantherClient()
- firebase - Flutter WEB:Firebase:未创建 Firebase 应用“[DEFAULT]”