如何使用带有react-animations的样式组件制作slideIn和slideOut

时间:2018-04-17 10:21:36

标签: css reactjs styled-components react-animations

我正在制作一个显示noneblock的组件,具体取决于isActive道具。

我设法slideInDown使用react-animationsstyled-components这样做。{/ p>

import styled, { keyframes } from 'styled-components';
import { ifProp } from 'styled-tools';
import { slideInDown } from 'react-animations';

const slideInAnimation = keyframes`${slideInDown}`;

const MyComponent = styled.div`
  animation: 0.4s ${slideInAnimation};
  display: ${ifProp('isActive', 'block', 'none')};
`;

我现在需要slideOutUp。但是,我不确定如何同时实施slideInDownslideOutUp动画。

我将如何实现这一目标?

注意:有效。但我不知道如何让它滑入和滑出。我在下面尝试了类似的东西,但是没有用。

import styled, { keyframes } from 'styled-components';
import { ifProp } from 'styled-tools';
import { slideInDown, slideOutUp } from 'react-animations';

const slideInAnimation = keyframes`${slideInDown}`;
const slideOutAnimation = keyframes`${slideOutUp}`;

const MyComponent = styled.div`
  animation: 0.4s ${slideInAnimation}, 0.4s ${slideOutAnimation};
  display: ${ifProp('isActive', 'block', 'none')};
`;

2 个答案:

答案 0 :(得分:1)

我浏览了react-animations库,我发现slideOutUp设置了visibility: 'hidden.'

const slideOutUp: Animation = {
  from: {
    transform: translate3d(0, 0, 0)
  },
  to: {
    visibility: 'hidden',
    transform: translate3d(0, '-100%', 0)
  }
};

您可以使用animation-fill-mode: forwards,这有助于在动画结束后保留​​样式。

你可以这样做(它有效):

const MyComponent = styled.div`
  animation: ${ifProp(
    "isActive",
    `0.4s ${slideInAnimation}`,
    `0.4s ${slideOutAnimation} forwards`
  )};
`;

以下是工作示例,用于测试目的onClick事件我正在设置{isActive: false}

https://codesandbox.io/s/949ql6p6no

答案 1 :(得分:0)

Display没有动画效果。您需要使用不透明度来切换(1到0,反之亦然)和动画。

const myComponent = styled.div`
  animation: 0.4s ${slideInAnimation};
  opacity: ${ifProp('isActive', 1, 0)};
`;

考虑到你的代码就像你告诉我的那样,你可以在动画中使用属性infinte:

animation: 0.4s ${slideInAnimation} infinite;

我想这可以解决你的问题。