如何使用 React TransitionMotion willEnter()

How to use React TransitionMotion willEnter()

使用 React Motion's TransitionMotion,我想为 1 个或多个方框制作动画。当一个盒子进入视图时,它的宽度和高度应该从 0 像素到 200 像素,它的不透明度应该从 0 到 1。当盒子离开视图时,相反的情况应该发生(width/height = 0,不透明度= 0)

我已尝试在此处解决此问题 http://codepen.io/danijel/pen/RaboxO 但我的代码无法正确转换框。框的样式立即跳转到 width/height 200 像素而不是过渡。

代码有什么问题?

let Motion = ReactMotion.Motion
let TransitionMotion = ReactMotion.TransitionMotion
let spring = ReactMotion.spring
let presets = ReactMotion.presets

const Demo = React.createClass({
  getInitialState() {
    return {
      items: []
    }
  },
  componentDidMount() {

    let ctr = 0

    setInterval(() => {
      ctr++
      console.log(ctr)
      if (ctr % 2 == 0) {
        this.setState({
          items: [{key: 'b', width: 200, height: 200, opacity: 1}], // fade box in
        });
      } else {
        this.setState({
          items: [], // fade box out
        });
      }

    }, 1000)
  },
  willLeave() {
    // triggered when c's gone. Keeping c until its width/height reach 0.
    return {width: spring(0), height: spring(0), opacity: spring(0)};
  },

  willEnter() {
    return {width: 0, height: 0, opacity: 1};
  },

  render() {
    return (
      <TransitionMotion
        willEnter={this.willEnter}
        willLeave={this.willLeave}
        defaultStyles={this.state.items.map(item => ({
          key: item.key,
          style: {
            width: 0, 
            height: 0,
            opacity: 0
          },
        }))}
        styles={this.state.items.map(item => ({
          key: item.key,
          style: {
            width: item.width, 
            height: item.height,
            opacity: item.opacity
          },
        }))}
        >
        {interpolatedStyles =>
          <div>
            {interpolatedStyles.map(config => {
              return <div key={config.key} style={{...config.style, backgroundColor: 'yellow'}}>
                <div className="label">{config.style.width}</div>
              </div>
            })}
          </div>
        }
      </TransitionMotion>
    );
  },
});

ReactDOM.render(<Demo />, document.getElementById('app'));

根据 stylesTransitionMotion 部分的 documentation(我并不声称已经理解了所有内容完全 :)):

styles: ... an array of TransitionStyle ...

这里要注意的关键是这个库处理了 2 种类型的 style 对象(或者至少是它的 TransitionMotion 部分)和它称它们为 TransitionStyleTransitionPlainStyle.

先前传递到 styles 属性的值是 TransitionPlainStyle。将它们更改为 TransitionStyle 神奇地 开始动画 Enter 序列。

您可以在 here.

上阅读有关上述 2 种不同类型的更多信息
styles={this.state.items.map(item => ({
  key: item.key,
  style: {
    width: spring(item.width), 
    height: spring(item.height),
    opacity: spring(item.opacity)
  }
}))}

Forked codepen demo.

同样,我还没有完全理解它的内部工作原理。我只知道您的 styles 必须以上述方式进行更改才能使其正常工作。

如果有人也能在这方面教育我,我会很高兴。

希望这对您有所帮助。