希望我的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 (将#修改为@)