高阶组件包裹,组件跳转

This commit is contained in:
HuaYu 2023-01-14 15:39:33 +08:00
parent 2989baccdc
commit 249d0a5503
1 changed files with 20 additions and 0 deletions

View File

@ -0,0 +1,20 @@
import { useNavigate } from 'react-router-dom'
// 高阶组件包装useNavigate()功能
// 原因类组件中无法使用useNavigate(),会报错
// React Hook "useNavigate" cannot be called in a class component.
function WidthUseNavigate(WrapCompontent) {
// 设置别名
WrapCompontent.displayName = `widthUseNavigate${getDisplayName(WrapCompontent)}`
return function NavigateCompont() {
const navigate = useNavigate()
// 给传入的组件新增一个to方法传给原始组件的props在原始组件中通过this.props.to(参数)使用
return <WrapCompontent to={navigate}></WrapCompontent>
}
}
// 别名
function getDisplayName(WrapCompontent) {
return WrapCompontent.displayname || WrapCompontent.name || 'Component'
}
export default WidthUseNavigate