首页 > 解决方案 > 在 reactjs 上的按钮之间移动动画

问题描述

我正在做一个项目,我是动画新手,我的目标是当用户单击按钮变为活动状态并且一行将从按钮移动到按钮时来自一组按钮。我设法使按钮处于活动状态并更改颜色等,我唯一仍然无法做到的是从按钮移动到按钮的那条线。

这是我的 Reactjs 代码

 class AnimateButtonArea extends Component {
  constructor(props){
    super(props)
    this.state = {  active: 0 };

  }


  setActive = (key) => {
    this.setState({ active: key });
  }

  render() {
    return (
      <div className = "AnimateButtonArea">
        {data.AnimateButton.map((animateButton, key) => {
            return(
              <div key = {key} className = { this.state.active === key ? "AnimateButton active" : "AnimateButton"} >
                <Button type = {this.state.active === key ? "SofiaProBlackSmallActive" : "SofiaProBlackSmall"} onClick = {() => { this.setActive(key) }}  text = {animateButton.button} />
                <div className = "animatedLine" />
              </div>
            )
        })}
      </div>
    )
  }
}

export default AnimateButtonArea;

这是我的 Sass 代码

.AnimateButtonArea
  display: inline-block
  
.AnimateButton
  display: inline-block
  margin-right: 147px  

.AnimateButton.active .animatedLine
  position: relative
  height: 8px
  left: 24px
  background: var(--yellow)
  border-radius: 40px
  text-align: center
  animation: grow 0.4s ease-out

@keyframes grow
  0%
    width: 0%

  100%
    width: 100%

更新

现在我可以移动这条线但现在我想增加这条线然后减少并移动它

这是更新的 Reactjs 部分

  setActive = (key) => {
    this.setState({ active: key })
    
    var difference = key - this.state.active

    leftActive += 300 * difference

    style = { width: `calc(${leftActive}px + 120px)`}

    setTimeout(()=> this.beActive(leftActive), 1000)
  }

  beActive = (leftActive) => {
    style = { marginLeft: `calc(${leftActive}px)`, with: `120px`}
    console.log(style);
  }

标签: cssreactjsanimation

解决方案


我会将宽度传递给状态(this.state.activeWidth)并将其包含在线条样式对象中。{宽度:this.state.activeWidth}


推荐阅读