React本机Animated API无法使用重构

时间:2017-10-30 17:01:09

标签: reactjs react-native higher-order-components recompose

我有一个重组的HOC没有正常运行 - 只是在没有动画的情况下显示组件的最终值。作为常规类编写的相同组件表现良好。有人能告诉我是什么导致了这个问题,或者我将如何解决这个问题,以便它正常工作?

重组HOC组件:

const enhancer = compose(
  withState('slideAnim', 'setSlide', new Animated.Value(width)),
  withState('fadeAnim', 'setFadeAnim', new Animated.Value(0)),
  lifecycle({
    componentDidMount () {
      Animated.parallel([
        Animated.timing(this.props.slideAnim, {
          toValue: 0,
          duration: 500
        }),
        Animated.timing(this.props.fadeAnim, {
          toValue: 1,
          duration: 500
        })
      ]).start()
    }
  })
)

const ModalScene = ({ children, slideAnim, fadeAnim }) => {
  return (
    <Animated.View style={[styles, { opacity: fadeAnim, left: slideAnim }]}>
      {children}
    </Animated.View>
  )
}

常规课程:

class ModalScene extends React.Component {
  constructor (props) {
    super(props)

    this.state = {
      slideAnim: new Animated.Value(width),
      fadeAnim: new Animated.Value(0)
    }
  }

  componentDidMount () {
    Animated.parallel([
      Animated.timing(this.state.slideAnim, {
        toValue: 0,
        duration: 500
      }),
      Animated.timing(this.state.fadeAnim, {
        toValue: 1,
        duration: 500
      })
    ]).start()
  }

  render () {
    return (
      <Animated.View
        style={[
          styles,
          { opacity: this.state.fadeAnim, left: this.state.slideAnim }
        ]}
      >
        {this.props.children}
      </Animated.View>
    )
  }
}

2 个答案:

答案 0 :(得分:0)

您的代码是正确的,您只是忘记导出HOC,试试这个: export default enhancer(ModalScene);

答案 1 :(得分:0)

我有一个类似的问题,似乎是由动画对象的可变性引起的。为了确保为我的组件的每个实例创建了Animated.Value的实例,我必须使用另一种形式的withState,即将函数作为初始值的那种形式。尝试更改这些行:

withState('slideAnim', 'setSlide', new Animated.Value(width)),
withState('fadeAnim', 'setFadeAnim', new Animated.Value(0)),

withState('slideAnim', 'setSlide', () => new Animated.Value(width)),
withState('fadeAnim', 'setFadeAnim', () => new Animated.Value(0)),