簡體   English   中英

"如何將 React Router Link 組件的重定向延遲 1 秒?"

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM