如何在 React.js 上设置延迟功能?有没有办法在 react 路由中添加或删除类,以便页面可以转换?添加、删除或切换类应该每次都有效。是否可以使用延迟功能在路由上添加、删除或切换类?或者我可以为此使用第三方库吗?
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const BasicExample = () => (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>
);
const Home = () => (
<div>
<h2>Home</h2>
</div>
);
const About = () => (
<div>
<h2>About</h2>
</div>
);
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>Rendering with React</Link>
</li>
<li>
<Link to={`${match.url}/components`}>Components</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>Props v. State</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic} />
<Route
exact
path={match.url}
render={() => <h3>Please select a topic.</h3>}
/>
</div>
);
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
);
export default BasicExample;
最佳答案
我将 Paul 的上述答案修改为更新的功能组件:
import React, { useEffect } from "react";
import PropTypes from "prop-types";
import { Link, useHistory, useLocation } from "react-router-dom";
// Functional link component which delays page navigation
export const DelayLink = props => {
const { delay, onDelayStart, onDelayEnd, replace, to, ...rest } = props;
let timeout = null;
let history = useHistory();
let location = useLocation();
useEffect(() => {
return () => {
if (timeout) {
clearTimeout(timeout);
}
};
}, [timeout]);
const handleClick = e => {
// if trying to navigate to current page stop everything
if (location?.pathname === to) return;
onDelayStart(e, to);
if (e.defaultPrevented) {
return;
}
e.preventDefault();
timeout = setTimeout(() => {
if (replace) {
history.replace(to);
} else {
history.push(to);
}
onDelayEnd(e, to);
}, delay);
};
return <Link {...rest} to={to} onClick={handleClick} />;
};
DelayLink.propTypes = {
// Milliseconds to wait before registering the click.
delay: PropTypes.number,
// Called after the link is clicked and before the delay timer starts.
onDelayStart: PropTypes.func,
// Called after the delay timer ends.
onDelayEnd: PropTypes.func,
// Replace history or not
replace: PropTypes.bool,
// Link to go to
to: PropTypes.string
};
DelayLink.defaultProps = {
replace: false,
delay: 0,
onDelayStart: () => {},
onDelayEnd: () => {}
};
export default DelayLink;
关于reactjs - 如何在 react 路由中设置延迟功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49840197/