如何解决希望我的React元素/ ref进行交互/了解CSS动画
我已经能够在屏幕上移动myRef。我有另一个元素(firstJellyRef)当前正在整个屏幕上进行动画处理,我希望myRef在firstJellyRef顶部时,“知道”它位于其顶部,然后删除firstJellyRef。
这是我的React代码:
constructor(props){
super(props)
this.characterRef = React.createRef()
this.firstJellyRef = React.createRef()
document.addEventListener('keydown',this.handleKeyDown)
}
componentDidMount(){
this.characterRef.current.style.left = 0
this.characterRef.current.style.bottom = 0
this.firstJellyRef.current.style.right = 0
}
handleKeyDown = (event) => {
if (this.characterRef.current) {
if (event.key === 'ArrowRight') {
let currentLeft = parseInt(this.characterRef.current.style.left,10);
if (currentLeft >= 0 && currentLeft < 1600) {
currentLeft += 15
this.characterRef.current.style.left = `${currentLeft}px`;}
} else if (event.key === 'ArrowUp') {
let currentBottom = parseInt(this.characterRef.current.style.bottom,10)
if (currentBottom >= 0 && currentBottom < 1000){
currentBottom += 15
this.characterRef.current.style.bottom = `${currentBottom}px`}
} else if (event.key === 'ArrowDown') {
let currentBottom = parseInt(this.characterRef.current.style.bottom,10)
if (currentBottom > 0 && currentBottom < 1000){
currentBottom -= 15
this.characterRef.current.style.bottom = `${currentBottom}px`
}
} else if (event.key === 'ArrowLeft') {
let currentLeft = parseInt(this.characterRef.current.style.left,10);
if (currentLeft > 0 && currentLeft < 1600){
currentLeft -= 15
this.characterRef.current.style.left = `${currentLeft}px`;
}
}
}
if(this.firstJellyRef.current) {
console.log(this.firstJellyRef.current)
}
}
render(){
return(
<>
<img className="jellyfish1" alt="" src={JellyFish1} ref={this.firstJellyRef} width="50" height="50"></img>
<img className="character-img" alt="" ref={this.characterRef} src={this.props.character.image} width="100" height="100"/>
</>
)
}
}
这就是我在ms CSS中所拥有的:
@keyframes jellyfishanimation {
0% {
right: 0px;
top: 0px;
}
100% {
right: 2000px;
top: 0px;
}
}
.jellyfish1 {
animation-name: jellyfishanimation;
animation-duration: 30s;
position: absolute;
right: 0px;
top: 0px;
}
.character-img {
position: absolute;
left: 0;
bottom: 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。