React 样式组件淡出 in/fade

React styled-components fade in/fade out

我正在尝试构建一个 React 组件来处理淡入和淡出。在下面的代码中,如果我将 out 作为道具传递给组件,它会在动画出来之前显示为隐藏。我试图让它默认淡入,然后在我传入 out 道具时淡出。有人看到这个问题的解决方案吗?

import React from 'react';
import styled, { keyframes } from 'styled-components';

const fadeIn = keyframes`
  from {
    transform: scale(.25);
    opacity: 0;
  }

  to {
    transform: scale(1);
    opacity: 1;
  }
`;

const fadeOut = keyframes`
  from {
    transform: scale(1);
    opacity: 0;
  }

  to {
    transform: scale(.25);
    opacity: 1;
  }
`;

const Fade = styled.div`
  ${props => props.out ?
    `display: none;`
   : `display: inline-block;`
   }
  animation: ${props => props.out ? fadeOut : fadeIn} 1s linear infinite;
`;

function App() {
  return (
    <div>
      <Fade>&lt;test&gt;</Fade>
    </div>
  );
}

export default App;

WebpackBin running example

您的代码存在的问题是当 props.out 为真时,您将显示 属性 设置为 none。这就是您看不到任何动画的原因,因为在动画开始之前您已经隐藏了组件!

制作淡出动画的方法是改用可见性 属性 并在与动画所用时间相同的时间内进行过渡。 (参见 this old SO answer

像这样应该可以解决您的问题:

const Fade = styled.default.div`
  display: inline-block;
  visibility: ${props => props.out ? 'hidden' : 'visible'};
  animation: ${props => props.out ? fadeOut : fadeIn} 1s linear;
  transition: visibility 1s linear;
`;

const fadeIn = styled.keyframes`
  from {
    transform: scale(.25);
    opacity: 0;
  }

  to {
    transform: scale(1);
    opacity: 1;
  }
`;

const fadeOut = styled.keyframes`
  from {
    transform: scale(1);
    opacity: 1;
  }

  to {
    transform: scale(.25);
    opacity: 0;
  }
`;

const Fade = styled.default.div`
  display: inline-block;
  visibility: ${props => props.out ? 'hidden' : 'visible'};
  animation: ${props => props.out ? fadeOut : fadeIn} 1s linear;
  transition: visibility 1s linear;
`;

class App extends React.Component {
  constructor() {
    super()
    this.state = {
      visible: true,
    }
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        visible: false,
      })
    }, 1000)
  }

  render() {
    return (
      <div>
        <Fade out={!this.state.visible}>&lt;test&gt;</Fade>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>

<div id="root" />

注意:您的淡出动画的不透明度也从 0 变为 1,而不是相反。我也在代码段中修复了它。