我安装了react-router-dom v6,我想在以前版本的react-router-dom v5中使用基于类的组件this.props.history()
在执行某些操作后适用于重定向页面,但此代码不适用于 v6 。
在react-router-dom v6中有一个钩子useNavigate
对于功能组件,但我需要在类基础组件中使用它,请帮助我如何在类组件中使用导航?
在react-router-dom v6中,对历史记录的支持已被弃用,取而代之的是引入了导航。如果您想在特定事件成功时将用户重定向到特定页面,请按照以下步骤操作:
创建一个名为的文件withRouter.js
,并将下面给出的代码粘贴到该文件中:
import { useNavigate } from 'react-router-dom';
export const withRouter = (Component) => {
const Wrapper = (props) => {
const navigate = useNavigate();
return (
<Component
navigate={navigate}
{...props}
/>
);
};
return Wrapper;
};
现在,在您想要将用户重定向到特定路径/组件的任何基于类的组件中,导入上面的内容withRouter.js
文件在那里并使用this.props.navigate('/your_path_here')
重定向功能。
为了帮助您,下面给出了显示相同内容的示例代码:
import React from 'react';
import {withRouter} from '.your_Path_To_Withrouter_Here/withRouter';
class Your_Component_Name_Here extends React.Component{
constructor(){
super()
this.yourFunctionHere=this.yourFunctionHere.bind(this);
}
yourFunctionHere()
{
this.props.navigate('/your_path_here')
}
render()
{
return(
<div>
Your Component Code Here
</div>
)
}
}
export default withRouter(Your_Component_Name_Here);
上面的代码工作完美。这只是一个小的扩展。
如果你想要 onclick 函数,这里是代码:
<div className = "row">
<button className= "btn btn-primary"
onClick={this.yourFunctionHere}>RedirectTo</button>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)