首页 > 解决方案 > React:在组件首次安装时停止运行样式化组件动画

问题描述

我有一个styled-component接收道具来确定要使用的动画。这是控制一个箭头图标,当活动时旋转“打开”,非活动时保持“关闭”。

这是styled-component和 两个keyframes动画的样子:

const rotate_down = keyframes`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(90deg);
  }
`;

const rotate_up = keyframes`
  from {
    transform: rotate(90deg);
  }
  to {
    transform: rotate(0deg);
  }
`;

const OpenUserSettings = styled.div`
  cursor: pointer;
  width: 20px;
  height: 20px;
  transition: 0.3s;
  animation: ${props => (props.rotate ? rotate_down : rotate_up)} 0.5s ease
    forwards;
  margin-top: 2px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;

  & > img {
    width: 5px;
  }
`

传入的rotateprop 是一个布尔值,通过onClickReact 组件中的处理程序进行切换:

    <OpenUserSettings
      rotate={arrowDown}
      onClick={() => {
        this.setState(prevState => ({
          arrowDown: !prevState.arrowDown
        }));
      }}
    >
      <img src={OpenArrow} alt="menu drop down arrow" />
    </OpenUserSettings>

这是有效的,当点击箭头时,rotateprop 被传入并成功在和OpenUserSettings之间切换。rotate_uprotate_down keyframes

现在我的问题是,当 React 组件第一次挂载时,arrowDown默认设置为 false,这意味着rotateprop 将是 false。这会导致将styled-component动画设置rotate_up为第一次安装。我认为这很难想象,所以看看这个看看我在描述什么:

在此处输入图像描述

您可以看到页面刷新时rotate_up动画非常快速地触发。我需要箭头保持关闭状态,但我不需要rotate_up在第一次加载时触发动画来关闭它。这是react-transition-group我可以控制初始输入的情况还是可以用逻辑处理的情况?

标签: javascriptcssreactjsstyled-components

解决方案


我对堆栈溢出的第一个贡献,多么令人兴奋!

为了确保动画不会在挂载时呈现,请将您的状态初始化为真/假,我记得最初将我的状态设置为 null。

在您的样式化组件中,您可以将 null / true / false 作为 prop 传递,并在组件外部定义一个对 null / true / false 执行检查的函数。(我使用了 TypeScript,所以不要复制类型)

function showAnimationOrNot(status: boolean | null) {
  if (status === true) {
    return `animation: nameAnimationIn 1s ease forwards;`
  } else if (status === false) {
    return `animation: nameAnimationOut 1s ease-out forwards;`
  } else if (status === null) {
    return ""
  }
}

在您的样式组件中,只需添加一行:

${(props: PropsDisplay) => show(props.show)};

我就是这样做的,我相信还有更优雅的方法,但它确实起到了在安装时预先制作动画的技巧。

作为回报,如果有人知道如何在函数的返回中突出显示样式化的组件语法,例如我在这里使用的函数(来自上面的示例):

return `animation: comeout 1s ease-out forwards;`

一定要告诉我!寻找那个!谢谢你,祝你好运!

继续动画!:)


推荐阅读