我在重新渲染时隐藏的React组件上的动画过渡 [英] Animate transition on a react component that i hide on re-render

查看:405
本文介绍了我在重新渲染时隐藏的React组件上的动画过渡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用reactjs并拥有一个datepicker组件,当用户在component元素之外单击时,该对象会隐藏.

i m using reactjs and i have a datepicker component that i hide when the user clicks outside of the component element.

代码段如下:

`
class DatePicker extends Component{
   constructor(props){
      super(props)
      state= { focus: false }  // when focus: false i hide the dates component 
  }    
  .......
  render(){
    const { focus } = this.state

    return(
      <input type="text" placeholder="start date">
      <input type="text" placeholder="start date">
      {focus &&  <DatesContainer ...props>} // if focus==false i dont show the <DatesContainer> component.I need to hide it with fade out or something.
    )
  }
}`

因此,当用户在<DatesContainer/>之外单击时,焦点会更新为false,然后重新渲染,这一次<DatesContainer/>根本不会渲染,到目前为止效果很好.但是我需要用0.3s的动画将其隐藏.

So when the user clicks outside of the <DatesContainer/> the state.focus updates to false, the re-renders and, this time, the <DatesContainer/> is not render at all, so far so good. But i need to hide it with a 0.3s animation.

对此有何看法?

推荐答案

我将状态更新为具有transitioning属性.使用CSS动画或过渡效果以及一些条件渲染,我们可以将一个新类应用于DatesContainer,检测动画何时完成并将焦点状态更改为false.

I'd update the state to have a transitioning property. Using CSS animations or transitions, and some conditional rendering, we can apply a new class to the DatesContainer, detect when an animation is finished and change the focus state to false.

每次在状态下单击时,都必须将状态转换设置为true.

You'll have to set transitioning to true in the state whenever you click outside it.

可能看起来像这样:

@keyframes fadeOut {
    0% {
        opacity: 1;
    }
    100% {
        opacity: 0;
    }
}

.fading {
    animation-name: fadeOut;
    animation-duration: 0.3s;
    animation-fill-mode: forwards;
    will-change: opacity;
}

JS

//import your styles here

class DatePicker extends Component{
   constructor(props){
      super(props)
      state= { focus: false, transitioning: false }
  }    

  handleFade() {
    this.setState({transitioning: false})
  }

  render(){
    const { focus, transitioning } = this.state

    return(
      <input type="text" placeholder="start date">
      <input type="text" placeholder="start date">
      {focus &&  <DatesContainer 
                   className={transitioning === true ? "fading" : null} 
                   onAnimationEnd={transitioning === true ? () => this.handleFade() : null}
                 /> 
      }
    )
  }
}`

这篇关于我在重新渲染时隐藏的React组件上的动画过渡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆