React Native ScrollView组件实现上拉下滑背景色不同

2,180 阅读1分钟

方法一:通过设置contentInset实现

<ScrollView
        contentContainerStyle={styles.container}
        contentInset={styles.contentInset}
        ref={(view) => { this.myScrollView = view}}
>
    <View style={styles.header} />
    ……
    <TouchableOpacity
          style={styles.login}
          onPress={() => { this.myScrollView.scrollTo({y: 1000})}}>
          <Text>让我滚回去</Text>
    </TouchableOpacity>
</ScrollView>

contentInset: {
    top: -1000, left: 0, bottom: 0, right: 0
  },
header:{
    height: 1000,
    backgroundColor: '#3399ff',
  },

方法二:通过设置contentOffset实现

constructor(props) {
    super(props);
    this.state = {y: 0};
  }
changeScroll = (e) => {
    this.setState({y: e.nativeEvent.contentOffset.y});
  };
<ScrollView
        style={{backgroundColor: this.state.y < 0 ? '#3399ff': 'white'}}
        contentContainerStyle={styles.container}
        contentOffset={{x: 0, y: 0}}
        onScroll={this.changeScroll}
        ref={(view) => { this.myScrollView = view}}
>
    ……
    <TouchableOpacity
          style={styles.login}
          onPress={() => { this.myScrollView.scrollTo({y: 0})}}>
          <Text>让我滚回去</Text>
    </TouchableOpacity>
</ScrollView>

推荐使用方法一,因为点一次屏幕onScroll才变一次,如果按着屏幕上下拉就不能实现上下不同颜色了,必须松开手重新点才可以。