import NavBar from react-vanttype Props = title string righttext string back = voidconst Cpnavbar = props Props = const ClickLeft = = TODO 点击左侧返回按钮 if propsback return
在React中,可以通过使用useHistory hook来获取history对象。然后可以使用history对象的goBack方法来实现返回功能。
首先,需要在组件中引入useHistory:
import { useHistory } from 'react-router-dom';
然后在组件中使用useHistory:
const history = useHistory();
修改ClickLeft函数:
const ClickLeft = () => {
if (props.back) {
return props.back();
}
history.goBack();
};
完整的代码如下:
import { NavBar } from 'react-vant';
import { useHistory } from 'react-router-dom';
type Props = {
title?: string;
righttext?: string;
back?: () => void;
};
const Cpnavbar = (props: Props) => {
const history = useHistory();
const ClickLeft = () => {
if (props.back) {
return props.back();
}
history.goBack();
};
return (
<div>
<NavBar
title={props.title}
leftText="返回"
rightText={props.righttext}
onClickLeft={ClickLeft}
/>
</div>
);
};
export default Cpnavbar;
这样就可以在React中正确地获取history对象,并使用goBack方法实现返回功能
原文地址: http://www.cveoy.top/t/topic/iXcf 著作权归作者所有。请勿转载和采集!