3

我正在尝试使用React Motion UI Pack为我的侧边导航设置滑入/滑出动画。就是这个:

constructor(props){
  super(props);
  this.state = {
    isThere: false,
    showOverlay: false
  } 
  this.updatePredicate = this.updatePredicate.bind(this);
  this.handleToggleClick = this.handleToggleClick.bind(this);
  this.handleOverlayClick = this.handleOverlayClick.bind(this);
}

componentDidMount() {
  this.updatePredicate();
  window.addEventListener("resize", this.updatePredicate);
}

componentWillUnmount() {
  window.removeEventListener("resize", this.updatePredicate);
}

updatePredicate() {
  this.setState({ isThere: window.innerWidth > this.props.breakWidth })
}

handleToggleClick(){
  this.setState({
    isThere: true,
    showOverlay: true
  })
}

handleOverlayClick(){
  this.setState({
    isThere: false,
    showOverlay: false
  });
}

let sidenav = (
  <Tag {...attributes} className={classes} key="sidenav">
    <ul className="custom-scrollbar">
      {src &&
        <li>
          <div className="logo-wrapper">
            <a href={href}>
              <img src={src} className="img-fluid"/>
            </a>
          </div>
        </li>
      }
      {children}
    </ul>
  </Tag>
);

return (
  <div>
    { isThere ? (
      <Transition
      component={false}
      appear={{ opacity: 0.2, translateX: -300 }}
      enter={{ opacity: 1, translateX: 0 }}
      leave={{ opacity: 0.2, translateX: -300 }}
    >
        { sidenav }
      </Transition>
      ) : (
        <Button color="primary" onClick={this.handleToggleClick} key="sideNavToggles">ClickMe</Button>
      ) }
    {showOverlay && (
      <div id="sidenav-overlay" onClick={this.handleOverlayClick} key="overlay"></div>
    )}
  </div>
    );
  }
}

该实用程序看起来很棒,但是有些东西我无法理解。我的组件根据breakWith道具呈现按钮或sidenav。单击呈现的按钮会导致 SideNav 滑入,这一次与覆盖一起。Transition允许平滑的滑入动画,但现在我想在单击叠加层时应用滑出动画。

几个小时过去了,我开始认为这是不可能的。组件的渲染是有条件的和基于状态的(中的isThere ? (...部分render()),对吗?由于该包没有提供任何willLeave道具,因此似乎没有时间制作动画leave在状态变化和重新渲染之间设置动画,而条件渲染元素已经丢失。

还是我错过了什么?

4

1 回答 1

2

是的 -这里找到的答案有效地解决了这个问题。为了解决这个问题,我将组件的条件逻辑向上移动,创建了适当的变量,并将其封装在一个<Transition>in 中render()。如果这里有一个教训,那就是如果被条件语句包围<Transition>Reakt Motion UI Pack(也许还有其他地方)不会触发它的动画,如果你不这样leave做就不可能与它一起使用ternary operator希望false组件也被动画化。

于 2018-01-11T09:53:08.880 回答