[英]How to switch from one screen to another after a certain time in ReactJS?
I'm new to ReactJS and want to implement the following logic: I have an intro screen in my app and after a few seconds I require to swap the intro screen with the home page. 我是ReactJS的新手,想实现以下逻辑:我的应用程序中有一个简介屏幕,几秒钟后,我需要将简介屏幕与主页交换。
How can I do this? 我怎样才能做到这一点?
I have both the intro screen and home page in two separate components and I'm using React Router. 我在两个单独的组件中都有介绍屏幕和主页,并且我正在使用React Router。
I've been thinking of using a SetTimeOut
to change my components, but I don't know how to use it between components. 我一直在考虑使用
SetTimeOut
更改组件,但是我不知道如何在组件之间使用它。
Here is my App.js code: 这是我的App.js代码:
import React, {Component} from 'react';
import './App.css';
import {Route, Switch} from 'react-router-dom';
import Intro from './components/Intro';
import Home from './components/Home';
import Work from './components/Work';
import About from './components/About';
import Carrers from './components/Carrers';
import Contact from './components/Contact';
class App extends Component {
constructor(){
super()
}
render() {
return (
<React.Fragment>
<Switch>
<Intro path= "/" exact component={Intro}/>
<Route path= "/home" exact component={Home} />
<Route path= "/about" exact component={About} />
<Route path= "/work" exact component={Work} />
<Route path= "/carrers" exact component={Carrers} />
<Route path= "/contact" exact component={Contact} />
</Switch>
</React.Fragment>
);
}
}
export default App;
Could you please advise me on the right approach? 您能给我建议正确的方法吗?
Your intro component can be like this 您的介绍组件可以像这样
class Intro extends React.Component {
componentDidMount() {
setTimeout(() => {
this.props.history.push('/home')
}, 5000) // render for 5 seconds and then push to home
}
render() {
return <h1>render for 5 seconds and then push to home</h1>
}
}
Please refer to this question: Programmatically navigate using react router 请参考此问题: 使用React Router以编程方式导航
Basically, you will get history from props and will use it to push to new route. 基本上,您将从道具中获取历史记录,并将其用于新路线。
const { history } = this.props;
history.push('/new-location')
If you don't see it into your props because it's not the Component from your Route, you will need to use withRouter from 'react-router-dom'. 如果由于它不是Route中的组件而不在道具中看到它,则需要使用“ react-router-dom”中的withRouter。
import { withRouter } from 'react-router-dom';
export default withRouter(Component);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.