使用变换和过渡动画反应组件

animate react component with transform and transition

我使用这个内联转换在幻灯片上动态迭代

<div className="slides" style={{transform: `translate(${currentPosition}%, 0px)`, left: 0}}> {slider} </div>
</div>

工作正常。但是我想在位置更改时向该元素添加一些淡入淡出,并且以下 css 不起作用

元素幻灯片通过 css

opacity: 0;
animation: fadein 2s ease-in 1 forwards;

这是我的淡入动画

@keyframes fadein {
  from {
    opacity:0;
  }
  to {
    opacity:1;
  }
}

在这种情况下我缺少什么?

你可以尝试这样的事情。这会让您了解如何应用动画。

class Test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      currentPosition: 0,
      opacity: 0
    }
  }

  componentDidMount() {
    setTimeout(() => this.setState({
      opacity: 1
    }), 500);
  }

  handleClick() {
    let self = this;
    this.setState({
      opacity: 0
    }, () => setTimeout(() => self.setState({
      opacity: 1
    }), 2000))
  }

  render() {
    return ( <
      div >
      <
      div className = "slides"
      style = {
        {
          transform: `translate(${this.state.currentPosition}%, 0px)`,
          left: 0,
          opacity: this.state.opacity
        }
      } > Some title to test animation < /div> <
      button onClick = {
        this.handleClick.bind(this)
      } > Click < /button> <
      /div>
    )
  }
}

React.render( < Test / > , document.getElementById('container'));
.slides {
  transition: all 2s ease-in;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="container"></div>

Here is the fiddle.

希望对您有所帮助。