React样式组件淡入/淡出

时间:2017-01-31 19:31:44

标签: reactjs styled-components

我正在尝试构建一个React组件来处理淡入和淡出。在下面的代码中,如果我将out作为prop传递给组件,则在动画制作之前将其隐藏为隐藏。我试图让它在默认情况下淡入淡出,然后在我传入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

1 个答案:

答案 0 :(得分:13)

您的代码的问题是,当props.out为true时,您将display属性设置为none。这就是为什么你没有看到任何动画,因为在此之前甚至可以开始隐藏组件!

淡出动画的方法是使用visibility属性,并将其转换为与动画相同的时间。 (见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" />

注意:您的fadeOut动画也从0变为1不透明度,而不是相反。我已经在片段中解决了这个问题。