How does Animated.Event work in React Native?

后端 未结 3 887
长发绾君心
长发绾君心 2021-02-04 06:38

I\'m I understanding it correctly ? Does this two set of code meant the same thing ?Does it have any difference in performance or reliability ?



        
相关标签:
3条回答
  • 2021-02-04 06:56

    Yes there is a difference in semantic

     <ScrollView onScroll={Animated.event(
      [{nativeEvent: {contentOffset: {y: this.state.scrollY}}}]
    )}></ScrollView>
    

    The first one i.e the above Animated.event returns a function that sets the scrollview's nativeEvent.contentOffset.y to your current scrollY state which I assume is animated.

    The other code just sets scrollY to your scrollView's e.nativeEvent.contentOffset.y and causes a rerender to your component

    0 讨论(0)
  • 2021-02-04 07:03

    it's not the same. Animated.event is used to map gestures like scrolling, panning or other events directly to Animated values. so in your first example this.state.scrollY is an Animated.Value. you would probably have code somewhere that initialized it, maybe your constructor would looks something like this:

    constructor(props) {
      super(props);
      this.state = {
        scrollY: new Animated.Value(0)
      };
    }
    

    in your second example this.state.scrollY is the y value (just the number) that was triggered in the scroll event, but completely unrelated to animation. so you couldn't use that value as you could use Animated.Value in animation.

    it's explained here in the documentation

    0 讨论(0)
  • 2021-02-04 07:11

    If you want to handle the scroll you can use it this way:

    handleScroll = (event) => {
        //custom actions
    }
    
    <ScrollView
     onScroll={Animated.event(
    [{ nativeEvent: {
        contentOffset: {
          x: this.state.scrollY
         }
      }
    }],{
       listener: event => {
           this.handleScroll(event);
       }})
    }>
    </ScrollView>
    
    0 讨论(0)
提交回复
热议问题