如何在 React Native 中使用 Animated.diffClamp [英] How to use Animated.diffClamp in react native

查看:31
本文介绍了如何在 React Native 中使用 Animated.diffClamp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有关于如何实现 Animated.diffClamp 的代码示例?

Any code example of how to implement Animated.diffClamp?

我正在尝试创建一个标题滚动动画,就像 google play 应用程序中的那样.当您开始向下滚动时,我已经隐藏了标题,但问题是我想在您开始向上滚动时再次显示标题,它仅在您到达视图顶部时显示.

I'm trying to create a header scroll animation like the one featured in the google play app. I already hide the header when you start scrolling down, but the problem is that I want to show the header again as soon as you start scrolling up, it shows only when you reach the top of the view.

class Services extends Component {
  constructor(props){
  super(props);
  this.state = {
    scrollY : new Animated.Value(0),
  }
}

renderScrollViewContent(){
  return (
    <View style={styles.scrollViewContent}>
    </View>
  )
}

render() {
  const headerHeight = this.state.scrollY.interpolate({
    inputRange: [0, 60],
    outputRange: [0, -60],
    extrapolate: 'clamp'
  });

  return (
    <View style={styles.container}>
      <ScrollView style={styles.container}
        scrollEventThrottle={16}
        onScroll={Animated.event(
          [{nativeEvent: {contentOffset: {y: this.state.scrollY}}}]
        )}
      >
        {this.renderScrollViewContent()}
      </ScrollView>
      <Animated.View style={[styles.header, {top: headerHeight}]}>
        <View style={styles.bar}>
          <Text style={styles.title}>Title</Text>
        </View>
      </Animated.View>
    </View>
  );
 }
}

推荐答案

我们正是为此用例添加的.这是文档页面 https://reactnative.dev/docs/animated#diffclamp

We added this exactly for this use case. Here's the doc page https://reactnative.dev/docs/animated#diffclamp

我还建议将它与翻译转换一起使用(性能更好,可以与本机驱动程序一起使用).这是您使用它的示例渲染:

I also recommend using it with a translate transform (better perf and can be used with native driver). Here's your example render using it:

const headerTranslate = Animated.diffClamp(this.state.scrollY, 0, 60)
  .interpolate({
    inputRange: [0, 1],
    outputRange: [0, -1],
  });
 
return (
 <View style={styles.container}>
   <ScrollView style={styles.container}
     scrollEventThrottle={16}
     onScroll={Animated.event(
       [{nativeEvent: {contentOffset: {y: this.state.scrollY}}}]
     )}
   >
     {this.renderScrollViewContent()}
   </ScrollView>
   <Animated.View style={[styles.header, {transform: [{translateY: headerTranslate}]}]}>
     <View style={styles.bar}>
       <Text style={styles.title}>Title</Text>
     </View>
   </Animated.View>
 </View>
);

它的工作原理是我们将滚动位置传递给 diffClamp,因此在我们使用 interpolate 使值变为负值(我们希望它向上平移)之后,它被限制在 0 和 60 之间.

How it works is we pass the scroll position to diffClamp so it is clamped between 0 and 60, after we use interpolate to make the value negative (we want it to translate up).

这篇关于如何在 React Native 中使用 Animated.diffClamp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆