React Router:如何在BrowserRouter子组件中获取location以实现过渡动画
Solution: Get
location in IndexComponent for Route Transitions Got it, let's fix this up so you can add those smooth transitions to your routes. Since your IndexComponent is wrapped directly by BrowserRouter, it doesn't receive the location prop automatically—we need to grab it using React Router's built-in tools. Here's how to do it depending on your component type:
For Function Components (Recommended for Modern React)
Use the useLocation hook from react-router-dom to access the location object directly:
import { Switch, Route, useLocation } from 'react-router-dom'; import { CSSTransition, TransitionGroup } from 'react-transition-group'; function IndexComponent() { // Grab the location object with the useLocation hook const location = useLocation(); return ( <TransitionGroup> <CSSTransition key={location.key} classNames="fade" timeout={300}> {/* Important: Pass location to Switch to ensure correct route matching during animations */} <Switch location={location}> <Route exact path="/course_info/:id" component={CourseInfoPage} /> <Route exact path="/" component={Main} /> {/* Add your other routes here */} </Switch> </CSSTransition> </TransitionGroup> ); }
For Class Components
If you're using a class component, wrap it with the withRouter higher-order component to inject routing props like location:
import { Switch, Route, withRouter } from 'react-router-dom'; import { CSSTransition, TransitionGroup } from 'react-transition-group'; import React, { Component } from 'react'; class IndexComponent extends Component { render() { // Destructure location from props (injected by withRouter) const { location } = this.props; return ( <TransitionGroup> <CSSTransition key={location.key} classNames="fade" timeout={300}> <Switch location={location}> <Route exact path="/course_info/:id" component={CourseInfoPage} /> <Route exact path="/" component={Main} /> {/* Add your other routes here */} </Switch> </CSSTransition> </TransitionGroup> ); } } // Wrap the component with withRouter to get routing props export default withRouter(IndexComponent);
Key Notes to Make It Work
- Install
react-transition-group: If you haven't already, run this command in your project:npm install react-transition-group # or yarn add react-transition-group - Add CSS for Transitions: Define the CSS classes matching your
classNamesprop to make the fade animation visible:.fade-enter { opacity: 0; } .fade-enter-active { opacity: 1; transition: opacity 300ms ease-in; } .fade-exit { opacity: 1; } .fade-exit-active { opacity: 0; transition: opacity 300ms ease-out; } - Pass
locationtoSwitch: This is crucial! WhenCSSTransitionkeeps the previous route's DOM during the animation, theSwitchneeds the currentlocationto render the correct component—without this, you might see routing mismatches.
内容的提问来源于stack exchange,提问作者Poogy
相关产品推荐
相关产品推荐

