单击按钮时,React Router Change transitionName

时间:2017-06-22 14:12:26

标签: reactjs react-router

我已将CSSTransitionsGroup添加到我的React-Router以创建页面转换。现在,我希望根据我点击的链接进行不同的转换。 例如:我总是想使用'淡入淡出',除非我点击'工作'按钮,然后我想使用'slideLeft'。 我使用的是React-Router 4,以及来自https://facebook.github.io/react/docs/animation.html的普通React Animation Add-Ons。

我的路由器和转换的我的应用程序组件如下所示:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Route, Switch } from 'react-router-dom';
import { Provider } from 'react-redux';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup' // ES6
import { ConnectedRouter } from 'react-router-redux';

import createHistory from 'history/createBrowserHistory';

const history = createHistory();

import Home from '../containers/Home';
import Work from '../containers/Work';
import BTS from '../containers/BTS';
import SinglePage from '../containers/SinglePage';
import NotFound from '../containers/NotFound';
import store from '../store';

export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <ConnectedRouter history={history}>
          <Route render={({ location }) => (
            <CSSTransitionGroup
              transitionName="fade"
              transitionEnterTimeout={500}
              transitionLeaveTimeout={300}>
              <Switch key={location.key} location={location}>
                <Route exact path="/" component={Home}/>
                <Route exact path="/work" component={Work}/>
                <Route exact path="/behind-the-scenes" component={BTS}/>
                <Route path="/about" component={SinglePage}/>
                <Route component={NotFound}/>
              </Switch>
            </CSSTransitionGroup>
          )}/>
        </ConnectedRouter>
      </Provider>
    );
  }
}

我的Home组件只有3个简单按钮:

import React, { Component } from 'react';
import {connect} from 'react-redux';
import { Link, withRouter } from 'react-router-dom';

export default class Home extends Component{

  render() {
    return(
      <div className="home page">
        <main>
              <ul>
                <li><Link to="/work">Work</Link></li>
                <li><Link to="/behind-the-scenes">behind the scenes</Link></li>
                <li><Link to="/3eBtn">3e Btn</Link></li>
              </ul>
        </main>
      </div>
    )
  }
}

所以它总是使用Fade,因为我调用了transitionName="fade",但是当我点击'/ work'链接时我想调用'SlideLeft'。

1 个答案:

答案 0 :(得分:0)

试试这个:

将条件设置为transitionName的值,当位置为work时,然后分配SlideLeft,否则为fade

<CSSTransitionGroup 
    transitionName={location.pathName == "work" ? "SlideLeft" : "fade"}