【问题标题】:How to properly animate using CSS in React如何在 React 中使用 CSS 正确设置动画
【发布时间】:2017-12-27 19:42:08
【问题描述】:

我正在使用 React 为自己创建一个副项目网站,以便更好地理解它。我正在尝试为 div 设置动画以在用户滚动到其位置时淡入。我已经成功地使用了滚动事件来触发一个更改 div 类名的函数(根据我的理解,这应该会触发不透明度的转换)。但是,这不起作用;相反,这会导致仅显示 div 中的文本,而没有任何动画。我确定我设置 div 的类名的方式有问题,但不确定是什么,这里是代码:

class Home extends React.Component{
  constructor(){
    super()
    this.state = {
      name: "WhatIdo",
      firstTransitionPosition: 0
    }
    this.handleScroll = this.checkForScroll.bind(this)
    this.hasBeenSet = false
  }

  checkForScroll() {
    if (window.scrollY >= this.state.firstTransitionPosition && this.hasBeenSet == false) {
      console.log("this event is triggering")
      this.setState({name: "WhatIdo--visible"})
      this.hasBeenSet = true
    }
  }

  componentDidMount(){
    var transitionComp = this.refs.moveMe
    var topOfElement = transitionComp.getBoundingClientRect().top
    var heightOfElement = transitionComp.getBoundingClientRect().height
    this.setState({firstTransitionPosition: topOfElement - heightOfElement})
    window.addEventListener('scroll', this.handleScroll);
  }

  componentWillUnmount(){
       window.removeEventListener('scroll', this.handleScroll);
  }


  render(){
    return(
      <div>
        <h1 className="PageTitle">Portfolio</h1>
        <div className="AboutMe">
          some stuff here
        </div>
        <div ref="moveMe" className={this.state.name}>
          some more random stuff
        </div>
      </div>
    )
  }
}

还有 CSS:

.AboutMe {
  border-style: solid;
  border-color: black;
  border-width: thick;
  width: 600px;
  height: 300px;
  position: relative;
  left: 365px;
  bottom: 300px;
  -moz-animation: fadein 2s;
}

@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 2; }
}

.WhatIdo {
  border-style: solid;
  border-color: black;
  border-width: thick;
  width: 600px;
  height: 300px;
  position: relative;
  left: 365px;
  bottom: 100px;
  opacity: 0;
  transition: opacity 2s;
}

.WhatIdo--visible {
  opacity: 1
}

提前感谢您的帮助!

【问题讨论】:

  • 不透明度不采用大于 1 的数字。它是从 0 到 1 的“百分比”值(例如,0.5 表示 50%)
  • @SimonNußbaumer 感谢您注意到这一点!我已经解决了。显示中的主要错误仍然存​​在。

标签: css reactjs


【解决方案1】:

除非我遗漏了什么...当您将 this.state.nameWhatIdo 更改为 WhatIdo--visible 时,您将丢失 WhatIdo 类的所有样式,包括导致它的 transition 属性只是弹出。

找到一种方法来指定元素应该是可见的除了保留它的正常样式。例如,您可以简单地将 visible 类添加到元素中,并让 CSS 定义为 .WhatIdo.visible 以便它覆盖其他元素。

一种方法(在众多方法中)是使用模板字符串并修改您的状态以简单地指定元素可见性是真还是假,使其更加抽象和灵活地响应状态变化:

    <div ref="moveMe" className={`WhatIdo ${this.state.isVisible ? "visible" : ""}`}>
      some more random stuff
    </div>

【讨论】:

  • 非常感谢您的回答,这非常有效;我已经向 state 添加了一个 isVisible 属性,该属性根据滚动位置设置为 true 或 false,然后应用其余的答案,这很有效。标记为正确答案:)
猜你喜欢
  • 2018-12-11
  • 2018-03-19
  • 1970-01-01
  • 2022-08-19
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 2014-03-12
相关资源
最近更新 更多