如何使用React TransitionMotion willEnter()

Lea*_*ner 6 javascript reactjs react-jsx react-motion

使用React Motion的TransitionMotion,我想要进出一个或多个框的动画.当一个框进入视图时,它的宽度和高度应该从0像素到200像素,并且它的不透明度应该从0到1.当框离开视图时,反向应该发生(宽度/高度= 0,不透明度= 0 )

我试图解决这个问题http://codepen.io/danijel/pen/Rabo​​xO但我的代码无法正确转换框.盒子的样式立即跳到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'));
Run Code Online (Sandbox Code Playgroud)

Tah*_*med 8

按照该文件stylesTransitionMotion部分(我不声称已经完全了解这一切:)):

styles:... TransitionStyle的数组......

这里要注意的关键一点是,有2种风格的对象与(或至少这个这个库交易TransitionMotion的一部分),并呼吁他们TransitionStyleTransitionPlainStyle.

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

您可以在此处阅读有关上述2种不同类型的更多信息.

styles={this.state.items.map(item => ({
  key: item.key,
  style: {
    width: spring(item.width), 
    height: spring(item.height),
    opacity: spring(item.opacity)
  }
}))}
Run Code Online (Sandbox Code Playgroud)

分叉的codepen演示.

同样,我还没有完全理解它的内部运作.我只知道你styles必须以上述方式改变它才能使它发挥作用.

如果有人可以就此教育我,我会很高兴.

希望这可以帮助.