javascript - 使用 react-router 为单个路由设置动画

标签 javascript reactjs react-router

我正在使用 react-router,我希望能够在安装和卸载时渲染和转换任意组件。现在我已经将组件添加到我的路由定义中:

<Route component={App}>
    <Route
      path="foo"
      component={Foo}
    />
    <Route
      path="bar"
      component={Bar}
    />
</Route>

我在我的组件中使用 react css transition group 在它们进入和离开时为它们设置动画。组件在进入时会安装和动画属性。但是当我离开路由时,渲染的组件会立即被移除,因此没有离开动画。

典型的解决方案是将过渡组添加到父级,这样它就不会被卸载,然后从那里为子级设置动画。这对我不起作用,因为 Foo 组件和 Bar 组件使用完全不同的动画。

简而言之,我认为我需要一种方法来单独为路线设置动画,而不是典型的“路线之间的过渡”。例如,在 //foo 之间导航应该产生以下结果:

  1. / 上,导航到 /foo -> Foo 组件动画。
  2. /foo 上,导航到其他任何地方,例如 / -> Foo 组件动画化。

我希望这是有道理的,谢谢!

最佳答案

也许,你可以延迟过渡,以允许完成“离开”动画

1) onChange jsfiddle 示例:https://jsfiddle.net/qnpj0odc/7/

const func = ({location:{pathname:prev}}, nextState, replace, callback)=>{
    prev=="/foo" ? setTimeout(callback,3000)
    :prev=="/bar" ? setTimeout(callback,2000)
    :callback();
};

<Route  path="/" component={App} onChange={func}>
    <Route path="foo" component={Foo} />
    <Route path="bar" component={Bar} />
</Route>

enter image description here


2) 与 setRouteLeaveHook https://jsfiddle.net/qnpj0odc/24/

class Foo extends React.Component{
  constructor(props){
    super(props);
    this.state={leave:0};
    props.router.setRouteLeaveHook(props.route,n=>this.startAnim(n))
  }
  startAnim(next){
    this.setState({leave:1});
    setTimeout(()=>{
      this.allow=1;
      this.props.router.push(next.pathname);},500)
    return !!this.allow;
  }
  render(){
    return (
        <h1 className={"animated zoomIn"+(this.state.leave?" zoomOut ":"")}>FOO</h1>
    );
  }
}

3) 与 listenBefore https://jsfiddle.net/qnpj0odc/23/

class Foo extends React.Component{
  constructor(props){
     super(props);
     this.state={leave:0};
     this.cb = props.router.listenBefore((loc,cb)=>{
       loc.pathname == props.location.pathname ?
       this.setState({leave:0}) :
       this.setState({leave:1},()=>setTimeout(cb,500))});
  }
  componentWillUnmount(){
    this.cb(); //unlisten
  }
  render(){
    return (
        <h1 className={"animated zoomIn"+(this.state.leave?" zoomOut ":"")}>FOO</h1>
    );
  }
}

关于javascript - 使用 react-router 为单个路由设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38319651/

相关文章:

javascript - 从 Ext.JS 按钮中删除右填充

javascript - React + Redux-router = Uncaught Error : Expected the reducer to be a function

javascript - react : Avoiding Re-rendering Same Component on Routing

javascript - React-router:防止导航到目标路线

javascript - React hook 状态对于几个相同的事件具有不同的值

javascript - jQuery.extend 一个对象,它是否存在?

javascript - 在 Ant Design Tree 中过滤 treeNodes

javascript - 如何将 jQuery 模式更改为 React 模式?

javascript - 如何延迟传递 props 直到 setState() 完成?

javascript - 如何在 Meteor/React 中通过 onClick 将变量传递给函数?