gpt4 book ai didi

css - 如何在 React 中正确地使用 CSS 制作动画

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:03 25 4
gpt4 key购买 nike

我正在使用 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
}

在此先感谢您的帮助!

最佳答案

除非我遗漏了什么...当您将 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>

关于css - 如何在 React 中正确地使用 CSS 制作动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45243004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com