React Router v4& CSS过渡组

时间:2017-07-01 10:15:13

标签: react-router-v4 reactcsstransitiongroup

我有一个简单的例子,反应路由器v4&路线过渡。它遵循https://reacttraining.com/react-router/web/example/animated-transitions中显示的示例。然而,结果只显示了最后一条路线。其他人只是空白。 https://codesandbox.io/s/r0PvB30wk

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import { CSSTransitionGroup } from 'react-transition-group'

import About from './components/About';
import Home from './components/Home';
import Topics from './components/Topics';

import './styles.css'

const BasicExample = () => (
  <Router>
    <Route render={({ location }) => (
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/topics">Topics</Link></li>
        </ul>

        <hr />
        <CSSTransitionGroup
          transitionEnterTimeout={300}
          transitionLeaveTimeout={300}
          transitionName="fade"
        >
          <Route exact path="/"       component={Home}   location={location} key={location.key} />
          <Route       path="/about"  component={About}  location={location} key={location.key} />
          <Route       path="/topics" component={Topics} location={location} key={location.key} />
        </CSSTransitionGroup>
      </div>
    )}/>
  </Router>
);

render(<BasicExample />, document.body);

2 个答案:

答案 0 :(得分:2)

对于任何有兴趣的人来说,唯一可以让它工作的方法就是使用来自react-router的<switch>

import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'
import { CSSTransitionGroup } from 'react-transition-group'

import About from './components/About'
import Home from './components/Home'
import Topics from './components/Topics'

import './styles.css'

const BasicExample = () => (
  <Router>
    <Route render={({ location, history, match }) => (
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/topics">Topics</Link></li>
        </ul>

        <hr />
        <CSSTransitionGroup
          transitionEnterTimeout={500}
          transitionLeaveTimeout={500}
          transitionName="fade"
        >
          <Switch key={location.key} location={location}>
            <Route exact path="/"       component={Home}   location={location} key={location.key} />
            <Route       path="/about"  component={About}  location={location} key={location.key} />
            <Route       path="/topics" component={Topics} location={location} key={location.key} />
          </Switch>
        </CSSTransitionGroup>
      </div>
    )}/>
  </Router>
)

render(<BasicExample />, document.body)

答案 1 :(得分:1)

你必须写代码这样的标签,否则它们就会消失......所以你要<Switch>? :)