【问题标题】:How does Animated.Event work in React Native?Animated.Event 在 React Native 中是如何工作的?
【发布时间】:2017-04-20 04:19:37
【问题描述】:

我理解正确吗? 这两组代码是不是同一个意思?在性能或可靠性上有什么区别吗?

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

handleScroll(e){
  this.setState({ scrollY : e.nativeEvent.contentOffset.y });
}

<ScrollView
 onScroll={(e) => this.handleScroll(e)}
>
</ScrollView>

谢谢

【问题讨论】:

    标签: react-native


    【解决方案1】:

    如果你想处理滚动,你可以这样使用它:

    handleScroll = (event) => {
        //custom actions
    }
    
    <ScrollView
     onScroll={Animated.event(
    [{ nativeEvent: {
        contentOffset: {
          x: this.state.scrollY
         }
      }
    }],{
       listener: event => {
           this.handleScroll(event);
       }})
    }>
    </ScrollView>
    

    【讨论】:

      【解决方案2】:

      不一样。 Animated.event 用于将滚动、平移或其他事件等手势直接映射到动画值。所以在你的第一个例子中this.state.scrollYAnimated.Value。你可能在某个地方有初始化它的代码,也许你的构造函数看起来像这样:

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

      在您的第二个示例中,this.state.scrollY 是在滚动事件中触发的 y 值(只是数字),但与动画完全无关。所以你不能像在动画中使用 Animated.Value 那样使用该值。

      it's explained here in the documentation

      【讨论】:

      • 一个是 Animated.Value 而另一个不是这一事实正是这两段代码之间的区别。你还能期待什么?
      【解决方案3】:

      根据this source code Animated.event 遍历作为它的参数传递的对象,直到找到 AnimatedValue 的实例。

      然后将这个键(已找到 AnimatedValue)应用于回调(onScroll),并将传递给滚动的事件键处的值分配给此 AnimatedValue。

      在代码中:

      const animatedValue = useRef(new Animated.Value(0)).current;
      ...
      onScroll={Animated.event(
        [{nativeEvent: {contentOffset: {y: animatedValue}}}]
      )}
      

      相同
      const animatedValue = useRef(new Animated.Value(0)).current;
      ...
      onScroll={({nativeEvent: { contentOffset: {y} }}) => {
        animatedValue.setValue(y);
      }}
      

      如果您的回调接受多个事件(参数),则只需将映射对象放在所需的索引处(因此将数组作为 Animated.value 的参数。

      onScroll={Animated.event(
        [
           {}, // <- disregard first argument of the event callback
           {nativeEvent: {contentOffset: {y: animatedValue}}} // <- apply mapping to the second 
        ]
      )}
      
      
      

      【讨论】:

        【解决方案4】:

        是的,语义上有区别

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

        第一个,即上面的 Animated.event 返回一个函数,将滚动视图的 nativeEvent.contentOffset.y 设置为您当前的滚动状态,我假设它是动画的。

        其他代码只是将 scrollY 设置为您的滚动视图的 e.nativeEvent.contentOffset.y 并导致重新渲染您的组件

        【讨论】:

          猜你喜欢
          • 2021-12-29
          • 2018-01-14
          • 2020-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-21
          • 2017-07-13
          相关资源
          最近更新 更多