2

我有一个在 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>
    )
  }
}
4

2 回答 2

0

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

于 2018-03-27T16:05:18.730 回答
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)),
于 2018-05-02T00:16:43.670 回答