Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

android - How to use Animated.diffClamp in react native

Any code example of how to implement Animated.diffClamp?

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>
  );
 }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We added this exactly for this use case. Here's the doc page https://facebook.github.io/react-native/docs/animated.html#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>
);

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...