【问题标题】:Change in CSS left property not animatingCSS left 属性的变化没有动画
【发布时间】:2020-07-23 17:24:43
【问题描述】:

在配方的步骤列表中,所有步骤divs 都显示在position: absolute 的容器中,带有overflow: hidden

如果是即将执行的步骤,则该步骤会隐藏在屏幕右侧,移动到当前步骤的中心(可见),然后移动到左侧。 (这被跟踪为currentness)。

export const CookingStep = ({ step, currentness }: Props) => {

  const StepWrapper = styled.div({
    width: '100%',
    background: 'lightgrey',
    height: '100px',
    position: 'absolute',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    transition: '1s ease',
    left: currentness! * 100 + '%' // left = -1, center = 0, right = 1
  })

  return <StepWrapper children={ step.text }/>
}

/* REDUX CONTAINER */

const selectProps = (state: RootState, ownProps: Props) =>
  ({ currentness: getCurrentness(ownProps.step)(state) })

const CookingStepContainer = connect(selectProps)(CookingStep)

export default CookingStepContainer

一切正常除了没有动画(来自transition 属性)。

当我更改步骤时,我非常确定我不会重新渲染 CookingStep 的父级(这会导致步骤被删除、不重新渲染或类似的事情,并阻止动画)。 我在StepsCarousel 中尝试了一条日志语句来查看它何时呈现,并且它只呈现一次(在启动时)。

// Wrappers are just styled components

const StepsCarousel = ({ steps, incStep, decStep }: Props) =>
  <CarouselWrapper>
    <Arrow onClick={ incStep }>{ "<" }</Arrow>
    <StepsWrapper>{
      steps.map((step, i) =>
        <CookingStepContainer step={ step } key={ i }/>
      )
    }</StepsWrapper>
    <Arrow onClick={ decStep }>{ ">" }</Arrow>
  </CarouselWrapper>

我已经在https://codesandbox.io/s/angry-grass-hjkw9 上模拟了整个 html/css 布局和动画行为,这让我花费了相当多的艰苦的脑力劳动时间,但动画效果却很完美。我看不出我在那里所做的和我在这里所做的有什么区别。

(在代码框上,我使用类名而不是直接使用样式组件设置left 属性。但实际上我也尝试在应用程序中使用类名,但无济于事。

为什么动画不工作?

【问题讨论】:

  • 您是否尝试过将当前性传递给 StepWrapper,然后在样式组件中以 props =&gt; props.currentness 的身份访问它
  • 哦,当然!每次渲染都会重新创建样式化组件!我还没有尝试过,但我会的,我相信你是对的。请写下作为答案,以便我可以在到期时给予信用。
  • 嘿,谢谢伙计,看看我的回答 :)

标签: css reactjs animation


【解决方案1】:

StyledWrapper 组件移出CookingStep 组件并将currentness 作为prop 传递给StyledWrapper

const StepWrapper = styled.div({
    width: '100%',
    background: 'lightgrey',
    height: '100px',
    position: 'absolute',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    transition: '1s ease',
    left: ${props => props.currentness! * 100 + '%'}
  })

export const CookingStep = ({ step, currentness }: Props) => {
  return <StepWrapper currentness={currentness} children={ step.text }/>
}

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2010-12-06
    相关资源
    最近更新 更多