[英]React Router: How to redirect to a different component when a link/button is clicked?
[英]How to delay the redirect of a React Router Link component for 1 second?
单击链接时,浏览器会尝试尽快重定向用户。 如何在此过程中添加 1 秒延迟?
我有以下链接:
<Link
to={{
pathname: `pathname`,
hash: `#hash`,
}}
onClick={this.delayRedirect}
>
import { withRouter } from 'react-router'
class Home extends Component {
delayRedirect = event => {
const { history: { push } } = this.props;
event.preventDefault();
setTimeout(()=>push(to), 1000);
}
};
<Link
to={{
pathname: `pathname`,
hash: `#hash`,
}}
onClick={this.delayRedirect}
>
}
export default withRouter(Home);
间隔一秒后使用历史推送新路线
这是我的函数组件版本,基于@Shishir 的回答:
import React from "react";
import { Link, useHistory } from "react-router-dom";
export default function CustomLink({ to, children }) {
const history = useHistory();
function delayAndGo(e) {
e.preventDefault();
// Do something..
setTimeout(() => history.push(to), 300);
}
return (
<Link to={to} onClick={delayAndGo}>
{children}
</Link>
);
}
根据 Pedro 的回答,这里有一种在 NavBar 等组件中添加 delayAndGo 函数的方法:
import React from "react"; import { Link, useHistory } from "react-router-dom"; export default function NavBar() { const history = useHistory(); function delayAndGo(e, path) { e.preventDefault(); // Do something.. setTimeout(() => history.push(path), 300); } return ( <Link to="/" onClick={(e) => delayAndGo(e, "/")}> </Link> <Link to="/about" onClick={(e) => delayAndGo(e, "/about")}> </Link> </Link> <Link to="/portfolio" onClick={(e) => delayAndGo(e, "/portfolio")}> </Link> ); }
请注意, Link
元素的to
值在此方法中无关紧要。
import loadable from '@loadable/component'
import pMinDelay from 'p-min-delay'
npm install p-min-delay
npm i @loadable/component
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.